標籤:
源地址:http://blog.shiqichan.com/using-afnetworking-sdwebimage-and-ohhttpstubs/
寫了個樣本,放在GitHub上。
這是啟動並執行動畫:
以下內容主要介紹:
- 基於AFNetworking的HTTP操作,GET擷取網頁和JSON資料,上傳檔案,下載檔案,以及載入圖片
- 基於SDWebimage的載入圖片
- 基於OHHTTPStubs的偽造網路響應用於測試(stub),而且可以類比出網路的延時
使用基於NSURLSession的AFNetworking API
AFNetworking有2套用於網路操作的API:
- 基於NSURLConnection
- 基於NSURLSession
後者是新的API,用於iOS 7 / Mac OS X 10.9及以上版本。
這篇文章寫的很好:從 NSURLConnection 到 NSURLSession,說明後者做了哪些改善和加強。
現在越來越多的iOS項目最低要求iOS 7,讓我們可以開始嘗試使用這種新的方式。
GET請求,擷取普通網頁文本
AFHTTPSessionManager是使用NSURLSession的API。
| 12345678910111213141516171819 |
NSURL *baseURL = [NSURL URLWithString:@"http://localhost/"]; //設定和加入頭資訊NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];[config setHTTPAdditionalHeaders:@{ @"User-Agent" : @"My Browser"}]; AFHTTPSessionManager *manager=[[AFHTTPSessionManager alloc] initWithBaseURL:baseURL sessionConfiguration:config];manager.responseSerializer = [AFHTTPResponseSerializer serializer];manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"]; //設定GET請求的參數NSDictionary *params=[[NSDictionary alloc] initWithObjectsAndKeys:@"3",@"id",nil]; //發起GET請求[manager GET:@"" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {NSLog(@"HTML: %@", [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);} failure:^(NSURLSessionDataTask *task, NSError *error) {NSLog(@"visit error: %@",error);}]; |
為了方便測試,這個樣本裡寫了個簡單的Web Server,httpServer.js。
運行httpServer.js,需要安裝node.js環境。然後:
sudo node httpServer
我使用了80連接埠,在Mac環境下是需要root許可權的。
GET請求,擷取JSON資料
方法和GET請求網頁文本大同小異,個別參數或者設定對象上有不同:
| 12345678910111213 |
NSURL *baseURL = [NSURL URLWithString:@"http://localhost/"];NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];[config setHTTPAdditionalHeaders:@{ @"User-Agent" : @"My Browser"}]; AFHTTPSessionManager *manager=[[AFHTTPSessionManager alloc] initWithBaseURL:baseURL sessionConfiguration:config];NSDictionary *params=[[NSDictionary alloc] initWithObjectsAndKeys:@"8",@"id",nil]; [manager GET:@"/json" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {NSDictionary * object=(NSDictionary *)responseObject;NSLog(@"response message: %@",object[@"message"]);} failure:^(NSURLSessionDataTask *task, NSError *error) {NSLog(@"visit error: %@",error);}]; |
下載檔案
AFNetworking API會返回NSURLSessionDownloadTask,可用於網路請求的取消、暫停和恢複。
其實上文中的GET方法也返回了這個對象,只不過下載檔案時間可能會較長,有可能有這方面的需求。
| 1234567891011121314 |
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; NSURL *URL = [NSURL URLWithString:@"http://www.baidu.com/img/bdlogo.png"];NSURLRequest *request = [NSURLRequest requestWithURL:URL]; NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {NSLog(@"File downloaded to: %@", filePath);uploadFilePath=filePath;}];[downloadTask resume]; |
使用AFNetworking載入圖片
需要引入一下:
| 1 |
#import <UIImageView+AFNetworking.h> |
然後,UIImageView就會有setImageWithURL供使用。
| 12 |
NSURL *URL = [NSURL URLWithString:@"http://www.baidu.com/img/bdlogo.png"];[imageView setImageWithURL:URL]; |
另外,提供了其他方法,可設定佔位圖片,圖片下載成功和失敗的處理,以及停止圖片下載的方法。
| 1234 |
– setImageWithURL:– setImageWithURL:placeholderImage:– setImageWithURLRequest:placeholderImage:success:failure:– cancelImageRequestOperation |
使用SDWebimage載入圖片
SDWebImage,調用方式和AFNetworking類似,功能更強大,使用也很普及。
需要引入:
| 1 |
#import <SDWebImage/UIImageView+WebCache.h> |
代碼:
| 12 |
NSURL *URL = [NSURL URLWithString:@"http://www.sogou.com/images/logo/new/sogou.png"];[imageView sd_setImageWithURL:URL]; |
下面是完整的方法列表:
| 123456789101112 |
– sd_imageURL– sd_setImageWithURL:– sd_setImageWithURL:placeholderImage:– sd_setImageWithURL:placeholderImage:options:– sd_setImageWithURL:completed:– sd_setImageWithURL:placeholderImage:completed:– sd_setImageWithURL:placeholderImage:options:completed:– sd_setImageWithURL:placeholderImage:options:progress:completed:– sd_setImageWithPreviousCachedImageWithURL:andPlaceholderImage:options:progress:completed:– sd_setAnimationImagesWithURLs:– sd_cancelCurrentImageLoad– sd_cancelCurrentAnimationImagesLoad |
比AFNetworking選項更多一些,比如可以設定SDWebImageOptions:
| 12345678910 |
typedef NS_OPTIONS(NSUInteger, SDWebImageOptions ) { SDWebImageRetryFailed = 1 < < 0, SDWebImageLowPriority = 1 < < 1, SDWebImageCacheMemoryOnly = 1 < < 2, SDWebImageProgressiveDownload = 1 < < 3, SDWebImageRefreshCached = 1 < < 4, SDWebImageContinueInBackground = 1 < < 5, SDWebImageHandleCookies = 1 < < 6, SDWebImageAllowInvalidSSLCertificates = 1 < < 7,}; |
還有:typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize)
- 可以用一組圖片產生動畫:sd_setAnimationImagesWithURLs
- 使用之前的Cache先顯示圖片?sd_setImageWithPreviousCachedImageWithURL,這個我從字面意思理解,還沒有使用
- 有個process block,
sd_setImageWithURL:placeholderImage:options:progress:completed:,可以獲得receivedSize和expectedSize位元組參數,用來顯示進程百分比
另外,iOS image caching. Libraries benchmark (SDWebImage vs FastImageCache),這篇文章測試和對比,結論也是SDWebimage更好一些。
AFNetworking上傳檔案
| 12345678910111213141516 |
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://localhost/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {[formData appendPartWithFileURL:uploadFilePath name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];} error:nil]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];NSProgress *progress = nil; NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {if (error) {NSLog(@"Error: %@", error);} else {NSLog(@"%@ %@", response, responseObject);}}]; [uploadTask resume]; |
可以通過NSProgress擷取上傳進度(具體怎麼做呢?)
使用OHHTTPStubs偽造HTTP響應
OHHTTPStubs,可用來偽造HTTP響應,這樣不依賴伺服器端,iOS的開發人員就可以測試網路服務了。
這個API,同時支援:
- NSURLConnection
- NSURLSession
不過,有個問題需要注意,如果App要上AppStore,是不能串連OHHTTPStubs的。
下面說下怎麼使用,先看代碼:
| 123456789101112131415 |
NSString *baseUrl=@"http://localhost"; //針對http://locahost/json請求的mock[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { NSDictionary *params=[NSDictionary objectsFromURLQueryString:request.URL.query];NSLog(@"id: %@",params[@"id"]); return [[request.URL absoluteString] rangeOfString:[NSString stringWithFormat:@"%@/json",baseUrl]].location==0;} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {NSLog(@"reqeust: %@",request);NSString* fixture = OHPathForFileInBundle(@"test.json",nil);return [[OHHTTPStubsResponse responseWithFileAtPath:fixturestatusCode:200 headers:@{@"Content-Type":@"text/json"}]requestTime:0 responseTime:0];}]; |
基本思路是,調用方法,通過2個回調(Block)實現對指定HTTP請求的響應偽造:
在上述代碼裡還示範了:
- 如何從URL中提取GET請求的參數,這裡用到了:URLQueryToCocoa
- 使用本地檔案作為JSON資料,加入到HTTP響應中
- 可以佈建要求和響應的延時,
requestTime:0 responseTime:0,這個相當有用
還可以用於偽造圖片的響應,測試了一下,上述的AFNetworking以及SDWebimage都有效。
| 12345678910 |
//GET image with sdwebimage[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {return [[request.URL absoluteString] isEqualToString:@"http://www.sogou.com/images/logo/new/sogou.png"];} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {NSLog(@"reqeust: %@",request);NSString* fixture = OHPathForFileInBundle(@"taobao.png",nil);return [[OHHTTPStubsResponse responseWithFileAtPath:fixturestatusCode:200 headers:@{@"Content-Type":@"image/png"}]requestTime:0 responseTime:0];}]; |
測試的時候,要注意,之前可能是通過真實網路擷取的,因此會有緩衝。需要把App刪除,重新安裝測試。
應該能看到類似下面的效果(使用的時本地圖片了):
OHHTTPStubs這些代碼,只需在App啟動載入一次即可,可寫在AppDelegate中:
| 123 |
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {[[AFNetworkReachabilityManager sharedManager] startMonitoring];[HttpMock initMock]; |
代碼屏蔽掉,自然就使用真實網路了。
編譯正式使用代碼的時候,可以考慮條件編譯。
AFNetworking的網路監控API
提供的AFNetworkReachabilityManager可以單獨使用,很方便,用於監控網路變化。
比如,可以在App啟動後執行下面操作,啟動監控器:
| 12 |
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {[[AFNetworkReachabilityManager sharedManager] startMonitoring]; |
在ViewController中:
| 123456 |
-(void)viewDidLoad{[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));}];} |
監聽網路變化,做出相應的操作,比如彈出提示框。
正式使用時:
- 可考慮在AppDelegate中
setReachabilityStatusChangeBlock,當狀態變化後,通過NSNotification發出通知
- 在各個ViewController的
viewDidAppear和viewWillDisappear中監聽和取消監聽通知
這是設想,還沒有付諸實施,也許還有問題。
不過至少不應該像本例中的,在ViewController中使用setReachabilityStatusChangeBlock。
iOS 8:【轉】使用AFNetworking, SDWebimage和OHHTTPStubs