除苹果提供的NSURLConnection和NSURLRequest外第三方的网络框架
1 安装和配置MKNetworkKit框架
下载并打开MKNetworkKit目录添加MKNetworkKit文件夹到新工程中-添加支持的类库或框架 CFNetwork.framework SystemConfiguration.framework Security.framework-添加预编译头文件
#ifndef MyNotes/MyNotes-Prefix.pch
#define MyNotes/MyNotes-Prefix.pch
#import <Foundation/foundation.h>
#endif
2 网络请求
MKNetworkOperation:封装了请求相应的类,我们需要为每一个网络请求创建一个MKNetworkOperation。
MKNetworkEngine:负责管理网络队列,简单请求时直接使用,复杂情况时可以子类化MKNetworkEngine。
1)实现GET请求
/* * 开始请求Web Service */ -(void)startRequest { 设置请求路径,它是主机名(域名或ip地址)之后的内容。 NSString *path = [[NSString alloc] initWithFormat:@"/service/mynotes/WebService.php?email=%@&type=%@&action=%@",@"<你的51work6.com用户邮箱>",@"JSON",@"query"]; 创建MKNetworkEngine对象,参数是主机名和请求头,主机名前面不加http或www。 MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"51work6.com" customHeaderFields:nil]; 创建MKNetworkOperation对象,参数是主机名之后的内容。其他参数有params:请求参数 httpMethod:指定请求方法 ssl:是否使用ssl加密请求 MKNetworkOperation *op = [engine operationWithPath:path]; 指定请求闭包,成功回调第一个代码块,失败回调第二个。 [op addCompletionHandler:^(MKNetworkOperation *operation) { 获取从服务器返回的NSData类数据 字符串 responseImage NSLog(@"responseData : %@", [operation responseString]); NSData *data = [operation responseData]; 解析数据 NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; [self reloadView:resDict]; } errorHandler:^(MKNetworkOperation *errorOp, NSError* err) { NSLog(@"MKNetwork请求错误 : %@", [err localizedDescription]); }]; 开始发起请求 [engine enqueueOperation:op]; }
2)实现POST请求
/* * 开始请求Web Service */ -(void)startRequest { NSString *path = [[NSString alloc] initWithFormat:@"/service/mynotes/WebService.php?email=%@&type=%@&action=%@",@"<你的51work6.com用户邮箱>",@"JSON",@"query"]; 为MKNetworkOperation指定请求参数 NSMutableDictionary *param = [[NSMutableDictionary alloc] init]; [param setValue:@"<你的51work6.com用户邮箱>" forKey:@"email"]; [param setValue:@"JSON" forKey:@"type"]; [param setValue:@"query" forKey:@"action"]; MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"51work6.com" customHeaderFields:nil]; MKNetworkOperation *op = [engine operationWithPath:path params:param httpMethod:@"POST"]; [op addCompletionHandler:^(MKNetworkOperation *operation) { NSLog(@"responseData : %@", [operation responseString]); NSData *data = [operation responseData]; NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; [self reloadView:resDict]; } errorHandler:^(MKNetworkOperation *errorOp, NSError* err) { NSLog(@"MKNetwork请求错误 : %@", [err localizedDescription]); }]; [engine enqueueOperation:op]; }
3 下载数据
MKNetworkOperation类不仅可以指定下载文件的位置,还可以获得下载的进度。
- (IBAction)onClick:(id)sender { 获取缓存目录 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *cachesDirectory = paths[0]; NSString *downloadPath = [cachesDirectory stringByAppendingPathComponent:@"test1.jpg"]; NSString *path = [[NSString alloc] initWithFormat:@"/service/download.php?email=%@&FileName=test1.jpg",@"<你的51work6.com用户邮箱>"]; path = [path stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"51work6.com" customHeaderFields:nil]; MKNetworkOperation *downloadOperation = [engine operationWithPath:path params:nil httpMethod:@"POST"]; 添加NSOutputStream输出流对象,它指定下载图片的位置。 [downloadOperation addDownloadStream:[NSOutputStream outputStreamToFileAtPath:downloadPath append:TRUE]]; 将下载进度进行日志输出 [downloadOperation onDownloadProgressChanged:^(double progress) { NSLog(@"download progress: %.2f%%", progress*100.0); _progressView.progress = progress; }]; 闭包 [downloadOperation addCompletionHandler:^(MKNetworkOperation *operation) { NSLog(@"download file finished!"); NSData *data = [operation responseData]; if (data) { //返回数据失败 NSError *eror; NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&eror]; if (!resDict) { NSNumber *resultCodeObj = [resDict objectForKey:@"ResultCode"]; NSString *errorStr = [resultCodeObj errorMessage]; UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"错误信息" message:errorStr delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; [alertView show]; } } else { //返回数据成功 UIImage *img = [UIImage imageWithContentsOfFile:downloadPath]; _imageView1.image = img; } } errorHandler:^(MKNetworkOperation *errorOp, NSError* err) { NSLog(@"MKNetwork请求错误 : %@", [err localizedDescription]); }]; [engine enqueueOperation:downloadOperation]; }
4 上传数据
- (IBAction)onClick:(id)sender { NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test2" ofType:@"jpg"]; NSString *path = [[NSString alloc] initWithFormat:@"/service/upload.php"]; NSMutableDictionary *param = [[NSMutableDictionary alloc] init]; [param setValue:@"<你的51work6.com用户邮箱>" forKey:@"email"]; MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"51work6.com" customHeaderFields:nil]; MKNetworkOperation *op = [engine operationWithPath:path params:param httpMethod:@"POST"]; 提供要上传的文件路径和文件类型 [op addFile:filePath forKey:@"file"]; 冻结操作:断网时保存数据 连网后自动上传保存的数据 [op setFreezable:YES]; [op addCompletionHandler:^(MKNetworkOperation *operation) { NSLog(@"Upload file finished!"); NSData *data = [operation responseData]; if (data) { NSError *eror; NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&eror]; if (resDict) {解析好的数据 NSNumber *resultCodeObj = [resDict objectForKey:@"ResultCode"]; NSString *errorStr = [resultCodeObj errorMessage];自定义 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"错误信息" message:errorStr delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; [alertView show]; return ; } } [self seeImage]; } errorHandler:^(MKNetworkOperation *errorOp, NSError* err) { NSLog(@"MKNetwork请求错误 : %@", [err localizedDescription]); }]; [engine enqueueOperation:op]; }
时间: 2024-10-25 11:48:45