標籤:
除蘋果提供的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];}
iOS 開發指南 第15章 訪問Web Service之使用輕量級網路請求架構MKNetworkKIt