CORE(核心):git
HTTP CLIENT :json
AFHTTPClient : 是一個封裝了基於http協議的網絡應用程序的公共交流模式緩存
IMAGES服務器
注意事項 :網絡
示例代碼 :app
get請求:異步
//GET請求 - (void)afGetMethod { //網絡請求的核心類,http請求的會話管理對象 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //設置響應數據的格式 //AFHTTPResponseSerializer 返回的數據類型爲二進制類型 //AFJSONResponseSerializer 返回數據類型爲json類型 //AFXMLParserResponseSerializer xml類型 manager.responseSerializer = [AFHTTPResponseSerializer serializer]; //get請求 //第一個參數:請求網址 //第二個參數:請求參數 //第三個參數:下載進度 //第四個參數:請求成功的block回調 //第五個參數:數據請求失敗 [manager GET:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { // NSLog(@"----------%@",responseObject);//所須要的數據 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil]; NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil]; NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",str); NSLog(@"%@",[NSThread currentThread]); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"請求失敗"); }]; }
post請求:post
//post請求 - (void)afPostMethd { //會話管理對象 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //設置返回數據的格式 manager.responseSerializer = [AFHTTPResponseSerializer serializer]; //轉義字符 // NSString *dict1 = @"{\\"data\\":20151031,\\"startRecord\\":1,\\"len\\":5,\\"udid\\":1234567890,\\"terminalType\\":\\"Iphone\\",\\"cid\\":213}"; NSDictionary *dict = @{@"data":@"20151031",@"startRecord":@"1",@"len":@"5",@"udid":@"1234567890",@"terminalType":@"Iphone",@"cid":@"213"}; //對象類型轉json串 // NSData *strData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil]; // NSString *jsonStr = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding]; // NSLog(@"%%"); //constructingBodyWithBlock:在此block種能夠爲上傳的參數添加(拼接)新的須要的上傳的數據,適用於上傳給服務器的數據流比較大的時候 //af中通常post請求的參數都爲字典類型 [manager POST:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx" parameters:dict constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil]; NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil]; NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"-------------***%@",str); NSLog(@"%@",[NSThread currentThread]); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"請求失敗"); }]; }
網絡監測 :測試
AppDelegate.m文件中ui
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
//開始監測 [manager startMonitoring]; //網絡狀態的返回 [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { //當網絡發生變化的時候,咱們發送通知,告知須要此消息的對象 [[NSNotificationCenter defaultCenter] postNotificationName:kNetStatus object:@(status)]; }];
ViewController.m文件中
//添加一個觀察者,觀察網絡的變化 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netChange:) name:kNetStatus object:nil]; //通知的回調方法 - (void)netChange:(NSNotification*)notification { //取出網絡狀態 AFNetworkReachabilityStatus status = [notification.object intValue]; switch (status) { case AFNetworkReachabilityStatusUnknown: NSLog(@"未知狀態"); break; case AFNetworkReachabilityStatusNotReachable: NSLog(@"無網絡鏈接"); break; case AFNetworkReachabilityStatusReachableViaWWAN: NSLog(@"3G/4G"); break; case AFNetworkReachabilityStatusReachableViaWiFi: NSLog(@"WiFi"); break; default: break; } }
上傳與下載
#pragma mark - 上傳 //有兩種方式 //第一種方法是經過工程中的文件進行上傳 - (void)upLoad1 { //1.建立管理者對象 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //2.上傳文件 NSDictionary *dict = @{@"username":@"1234"}; //上傳至哪一個url NSString *url = @"1235466"; [manager POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { //上傳文件參數 UIImage *image = [UIImage imageNamed:@"4.png"]; NSData *data = UIImagePNGRepresentation(image); //這個就是參數 [formData appendPartWithFileData:data name:@"file" fileName:@"4.png" mimeType:@"image/png"]; } progress:^(NSProgress * _Nonnull uploadProgress) { //打印上傳進度 NSLog(@"%lf",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"請求成功"); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"請求失敗"); }]; } //第二種:是經過url來獲取路徑,進入沙盒或者系統相冊等等 - (void)upload2 { //1.建立管理者對象 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //2.上傳文件 NSDictionary *dic = @{@"userName":@"123456"}; NSString *urlString = @"456789"; [manager POST:urlString parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"文件地址"] name:@"fileName" error:nil]; } progress:^(NSProgress * _Nonnull uploadProgress) { NSLog(@"%lf",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"請求成功: %@",responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"請求失敗: %@",error); }]; }
#pragma mark - 下載 - (void)downLoad { //1.建立管理者對象 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //2.肯定請求的URL地址 NSURL *url = [NSURL URLWithString:@""]; //3.建立請求對象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //下載任務 NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) { //打印下載進度 NSLog(@"%lf",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount); } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { //下載地址 NSLog(@"默認下載地址 : %@",targetPath); //設置下載路徑,經過沙盒獲取緩存地址,最後返回NSURL對象 NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; return [NSURL URLWithString:filePath]; } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { //下載完成調用的方法 NSLog(@"下載完成"); NSLog(@"%@--%@",response,filePath); }]; //開始啓動任務 [task resume]; }