因爲博客遷移至www.coderyi.com,文章請看http://www.coderyi.com/archives/422php
MKNetWorkKit是由一個印度小夥子寫的,是用於網絡請求的庫,支持ARC,代碼的網址這裏給出。ios
做者源碼地址(MugunthKumar):https://github.com/MugunthKumar/MKNetworkKitgit
做者關於類庫介紹的地址(MugunthKumar):http://blog.mugunthkumar.com/products/ios-framework-introducing-mknetworkkit/github
做者類庫介紹中文翻譯地址(翻譯做者,csdn博主kmyhy,楊宏焱):http://blog.csdn.net/kmyhy/article/details/12276287api
這裏面大多數時候會引用到它裏面的demo,MKNetWorkKit-iOS-Demo,本文主要是根據做者原文以及做者的demo還有本身的使用寫的文章。緩存
MKNetWorkKit中主要有兩個類,MKNetworkEngine和MKNetworkOperation,MKNetworkOperation就是一個操做,是NSOperation的子類,每一個HTTP操做經過MKNetworkEngine入隊,隊列是一個NSOperationQueue,在程序是一個單例,在MKNetworkEngine的initialize裏建立。網絡
通常本身會複寫MKNetworkEngine,在這裏提供一個每個網絡請求的接口,能夠傳入參數,請求完成和失敗的block。app
self.yahooEngine = [[YahooEngine alloc] initWithHostName:@"download.finance.yahoo.com"];
YahooEngine的GET請求方法的申明fetch
typedef void (^CurrencyResponseBlock)(double rate); -(MKNetworkOperation*) currencyRateFor:(NSString*) sourceCurrency inCurrency:(NSString*) targetCurrency completionHandler:(CurrencyResponseBlock) completion
GET請求方法的實現url
-(MKNetworkOperation*) currencyRateFor:(NSString*) sourceCurrency inCurrency:(NSString*) targetCurrency completionHandler:(CurrencyResponseBlock) completionBlock errorHandler:(MKNKErrorBlock) errorBlock { MKNetworkOperation *op = [self operationWithPath:YAHOO_URL(sourceCurrency, targetCurrency) params:nil httpMethod:@"GET"]; [op addCompletionHandler:^(MKNetworkOperation *completedOperation) { // the completionBlock will be called twice. // if you are interested only in new values, move that code within the else block NSString *valueString = [[completedOperation responseString] componentsSeparatedByString:@","][1]; DLog(@"%@", valueString); if([completedOperation isCachedResponse]) { DLog(@"Data from cache %@", [completedOperation responseString]); } else { DLog(@"Data from server %@", [completedOperation responseString]); } completionBlock([valueString doubleValue]); }errorHandler:^(MKNetworkOperation *errorOp, NSError* error) { errorBlock(error); }]; [self enqueueOperation:op]; return op; }
GET請求方法的調用
self.currencyOperation = [ApplicationDelegate.yahooEngine currencyRateFor:@"SGD" inCurrency:@"USD" completionHandler:^(double rate) { [[[UIAlertView alloc] initWithTitle:@"Today's Singapore Dollar Rates" message:[NSString stringWithFormat:@"%.2f", rate] delegate:nil cancelButtonTitle:NSLocalizedString(@"Dismiss", @"") otherButtonTitles:nil] show]; } errorHandler:^(NSError* error) { DLog(@"%@\t%@\t%@\t%@", [error localizedDescription], [error localizedFailureReason], [error localizedRecoveryOptions], [error localizedRecoverySuggestion]); }];
-(MKNetworkOperation*) uploadImageFromFile:(NSString*) file completionHandler:(IDBlock) completionBlock errorHandler:(MKNKErrorBlock) errorBlock { MKNetworkOperation *op = [self operationWithPath:@"upload.php" params:@{@"Submit": @"YES"} httpMethod:@"POST"]; [op addFile:file forKey:@"image"]; // setFreezable uploads your images after connection is restored! [op setFreezable:YES]; [op addCompletionHandler:^(MKNetworkOperation* completedOperation) { NSString *xmlString = [completedOperation responseString]; DLog(@"%@", xmlString); completionBlock(xmlString); } errorHandler:^(MKNetworkOperation *errorOp, NSError* error) { errorBlock(error); }]; [self enqueueOperation:op]; return op; }
上傳的時候能夠增長一個進度條,因此在調用這個方法的時候能夠有如下代碼。
NSString *uploadPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:@"/SampleImage.jpg"]; self.uploadOperation = [ApplicationDelegate.testsEngine uploadImageFromFile:uploadPath completionHandler:^(id twitPicURL) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Uploaded to" message:(NSString*) twitPicURL delegate:nil cancelButtonTitle:NSLocalizedString(@"Dismiss", @"") otherButtonTitles:nil]; [alert show]; self.uploadProgessBar.progress = 0.0; } errorHandler:^(NSError* error) { [UIAlertView showWithError:error]; }]; [self.uploadOperation onUploadProgressChanged:^(double progress) { DLog(@"%.2f", progress*100.0); self.uploadProgessBar.progress = progress; }];
正確顯示網絡狀態指示的判斷條件就是操做operation數大於0的時候。
在wifi以及3G網絡是會調用setMaxConcurrentOperationCount:方法切換最大操做數的大小。
MKNetWorkKit可以緩存你全部的GET請求,當請求相同時會調用本地緩存內容。
[self.yahooEngine useCache];
清空緩存使用以下方法
[ApplicationDelegate.yahooEngine emptyCache];
網絡斷開時的網絡請求會被凍結,經過NSKeyedArchiver序列化在本地,當有網時會再次請求。MKNetworkOperation的setFreezable:方法就是凍結操做。
[op setFreezable:YES];
相似的請求只請求一個操做
就是同一個URL只請求一次。
MKNetworkEngine的imageAtURL:completionHandler:errorHandler:方法可以緩存圖片。
[ApplicationDelegate.apiEngine imageAtURL:[NSURL URLWithString:(_strategyModel.titlepic)] completionHandler:^(UIImage* fetchedImage, NSURL* url, BOOL isInCache){ [iv setImage:fetchedImage]; }errorHandler:nil];
固然MKNetworkEngine的operationWithURLString: params: httpMethod:方法也能夠請求圖片,而且緩存,它其實就是根據一個URL地址來建立一個網絡線程,而後把它加入到隊列就能夠了。
MKNetworkOperation *op1 =[ApplicationDelegate.apiEngine operationWithURLString:_strategyModel.titlepic params:nil httpMethod:nil]; [op1 addCompletionHandler:^(MKNetworkOperation *completedOperation) { // [op1 responseImage]; [iv setImage:[completedOperation responseImage]]; } errorHandler:^(MKNetworkOperation *errorOp, NSError* error) { }]; [ApplicationDelegate.apiEngine enqueueOperation:op1];
其實MKNetworkOperation有各類response數據,這裏是responseImage,還有responseString、responseJSON、responseXML。
不過請求一個圖片還可使用MK提供的category,UIImageView+MKNetworkKitAdditions裏面的方法,以下,不過我試了以後好像沒有緩存,不過這個能夠用於tableview上每一個cell上顯示的圖片,比上面的要方便許多。
[self.thumbnailImage setImageFromURL:[NSURL URLWithString:self.loadingImageURLString] placeHolderImage:nil];
其實每個get請求都有緩存,要想知道你返回的數據是否緩存,能夠用如下方法。
[op addCompletionHandler:^(MKNetworkOperation *completedOperation) { // the completionBlock will be called twice. // if you are interested only in new values, move that code within the else block if([completedOperation isCachedResponse]) { DLog(@"Data from cache %@", [completedOperation responseString]); } else { DLog(@"Data from server %@", [completedOperation responseString]); } completionBlock([valueString doubleValue]); }errorHandler:^(MKNetworkOperation *errorOp, NSError* error) { errorBlock(error); }];
下載文件的時候也能夠增長進度條,方法相似上面上傳文件的使用,下載文件痛喲在操做上增長一個一個輸出流,下載文件的實現能夠以下。
-(MKNetworkOperation*) downloadFatAssFileFrom:(NSString*) remoteURL toFile:(NSString*) filePath { MKNetworkOperation *op = [self operationWithURLString:remoteURL]; [op addDownloadStream:[NSOutputStream outputStreamToFileAtPath:filePath append:YES]]; [self enqueueOperation:op]; return op; }