1 /** 2 要使用常規的AFN網絡訪問 3 4 1. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 5 6 全部的網絡請求,均有manager發起 7 8 2. 須要注意的是,默認提交請求的數據是二進制的,返回格式是JSON 9 10 1> 若是提交數據是JSON的,須要將請求格式設置爲AFJSONRequestSerializer 11 2> 若是返回格式不是JSON的, 12 13 3. 請求格式 14 15 AFHTTPRequestSerializer 二進制格式 16 AFJSONRequestSerializer JSON 17 AFPropertyListRequestSerializer PList(是一種特殊的XML,解析起來相對容易) 18 19 4. 返回格式 20 21 AFHTTPResponseSerializer 二進制格式 22 AFJSONResponseSerializer JSON 23 AFXMLParserResponseSerializer XML,只能返回XMLParser,還須要本身經過代理方法解析 24 AFXMLDocumentResponseSerializer (Mac OS X) 25 AFPropertyListResponseSerializer PList 26 AFImageResponseSerializer Image 27 AFCompoundResponseSerializer 組合 28 */ 29 30 - (void)viewDidLoad 31 { 32 [super viewDidLoad]; 33 34 [self reach]; 35 } 36 37 #pragma mark - 演練 38 #pragma mark - 檢測網絡鏈接 39 - (void)reach 40 { 41 /** 42 AFNetworkReachabilityStatusUnknown = -1, // 未知 43 AFNetworkReachabilityStatusNotReachable = 0, // 無鏈接 44 AFNetworkReachabilityStatusReachableViaWWAN = 1, // 3G 花錢 45 AFNetworkReachabilityStatusReachableViaWiFi = 2, // 局域網絡,不花錢 46 */ 47 // 若是要檢測網絡狀態的變化,必須用檢測管理器的單例的startMonitoring 48 [[AFNetworkReachabilityManager sharedManager] startMonitoring]; 49 50 // 檢測網絡鏈接的單例,網絡變化時的回調方法 51 [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { 52 NSLog(@"%d", status); 53 }]; 54 } 55 56 #pragma mark - Session 下載 57 - (void)sessionDownload 58 { 59 NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 60 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config]; 61 62 NSString *urlString = @"http://localhost/itcast/videos/01.C語言-語法預覽.mp4"; 63 urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 64 65 NSURL *url = [NSURL URLWithString:urlString]; 66 NSURLRequest *request = [NSURLRequest requestWithURL:url]; 67 68 NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 69 // 指定下載文件保存的路徑 70 // NSLog(@"%@ %@", targetPath, response.suggestedFilename); 71 // 將下載文件保存在緩存路徑中 72 NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]; 73 NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename]; 74 75 // URLWithString返回的是網絡的URL,若是使用本地URL,須要注意 76 NSURL *fileURL1 = [NSURL URLWithString:path]; 77 NSURL *fileURL = [NSURL fileURLWithPath:path]; 78 79 NSLog(@"== %@ |||| %@", fileURL1, fileURL); 80 81 return fileURL; 82 } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 83 NSLog(@"%@ %@", filePath, error); 84 }]; 85 86 [task resume]; 87 } 88 89 #pragma mark - POST JSON 90 - (void)postJSON 91 { 92 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 93 94 NSDictionary *dict = @{@"name": @"zhangsan"}; 95 NSDictionary *dict1 = @{@"name": @"wangwu"}; 96 NSArray *array = @[dict, dict1]; 97 // 設置請求格式 98 manager.requestSerializer = [AFJSONRequestSerializer serializer]; 99 // 設置返回格式 100 manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 101 102 [manager POST:@"http://localhost/postjson.php" parameters:array success:^(AFHTTPRequestOperation *operation, id responseObject) { 103 NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; 104 105 NSLog(@"%@", result); 106 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 107 108 }]; 109 110 } 111 112 #pragma mark - 隨機文件名上傳 113 - (void)postUpload1 114 { 115 // 本地上傳給服務器時,沒有肯定的URL,很差用MD5的方式處理 116 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 117 manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 118 119 [manager POST:@"http://localhost/demo/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 120 121 NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"頭像1.png" withExtension:nil]; 122 123 // 要上傳保存在服務器中的名稱 124 // 使用時間來做爲文件名 2014-04-30 14:20:57.png 125 // 讓不一樣的用戶信息,保存在不一樣目錄中 126 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 127 // 設置日期格式 128 formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss"; 129 NSString *fileName = [formatter stringFromDate:[NSDate date]]; 130 131 [formData appendPartWithFileURL:fileURL name:@"uploadFile" fileName:fileName mimeType:@"image/png" error:NULL]; 132 133 } success:^(AFHTTPRequestOperation *operation, id responseObject) { 134 NSLog(@"OK"); 135 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 136 NSLog(@"error"); 137 }]; 138 } 139 140 #pragma mark - POST上傳 141 - (void)postUpload 142 { 143 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 144 // AFHTTPResponseSerializer就是正常的HTTP請求響應結果:NSData 145 // 當請求的返回數據不是JSON,XML,PList,UIImage以外,使用AFHTTPResponseSerializer 146 // 例如返回一個html,text... 147 // 148 // 實際上就是AFN沒有對響應數據作任何處理的狀況 149 manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 150 151 // formData是遵照了AFMultipartFormData的對象 152 [manager POST:@"http://localhost/demo/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 153 154 // 將本地的文件上傳至服務器 155 NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"頭像1.png" withExtension:nil]; 156 157 [formData appendPartWithFileURL:fileURL name:@"uploadFile" error:NULL]; 158 } success:^(AFHTTPRequestOperation *operation, id responseObject) { 159 NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; 160 161 NSLog(@"完成 %@", result); 162 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 163 NSLog(@"錯誤 %@", error.localizedDescription); 164 }]; 165 } 166 167 #pragma mark - JSON 168 - (void)XMLData 169 { 170 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 171 172 // 返回的數據格式是XML 173 manager.responseSerializer = [AFXMLParserResponseSerializer serializer]; 174 175 NSDictionary *dict = @{@"format": @"xml"}; 176 177 // 網絡訪問是異步的,回調是主線程的,所以程序員不用管在主線程更新UI的事情 178 [manager GET:@"http://localhost/videos.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) { 179 180 // 若是結果是XML,一樣須要使用6個代理方法解析,或者使用第三方庫 181 // 第三方庫第三方框架,效率低,內存泄漏 182 NSLog(@"%@", responseObject); 183 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 184 NSLog(@"%@", error); 185 }]; 186 } 187 188 #pragma mark - JSON 189 - (void)JSONData 190 { 191 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 192 193 // 本來須要拼接get訪問URL ? & = 194 NSDictionary *dict = @{@"format": @"json"}; 195 196 // 網絡訪問是異步的,回調是主線程的,所以程序員不用管在主線程更新UI的事情 197 [manager GET:@"http://localhost/videos.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) { 198 NSLog(@"%@", responseObject); 199 // 提問:NSURLConnection異步方法回調,是在子線程 200 // 獲得回調以後,一般更新UI,是在主線程 201 NSLog(@"%@", [NSThread currentThread]); 202 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 203 NSLog(@"%@", error); 204 }]; 205 } 206 207 #pragma mark - POST登陸 208 - (void)postLogin 209 { 210 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 211 212 // 本來須要拼接get訪問URL ? & = 213 NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"}; 214 215 // 網絡訪問是異步的,回調是主線程的,所以程序員不用管在主線程更新UI的事情 216 [manager POST:@"http://localhost/login.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) { 217 NSLog(@"%@", responseObject); 218 // 提問:NSURLConnection異步方法回調,是在子線程 219 // 獲得回調以後,一般更新UI,是在主線程 220 NSLog(@"%@", [NSThread currentThread]); 221 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 222 NSLog(@"%@", error); 223 }]; 224 } 225 226 #pragma mark - GET登陸 227 - (void)getLogin 228 { 229 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 230 231 // 本來須要拼接get訪問URL ? & = 232 NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"}; 233 234 // 網絡訪問是異步的,回調是主線程的,所以程序員不用管在主線程更新UI的事情 235 [manager GET:@"http://localhost/login.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) { 236 NSLog(@"%@", responseObject); 237 // 提問:NSURLConnection異步方法回調,是在子線程 238 // 獲得回調以後,一般更新UI,是在主線程 239 NSLog(@"%@", [NSThread currentThread]); 240 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 241 NSLog(@"%@", error); 242 }]; 243 } 244