搞了兩年多iOS開發(fā)了褐隆,網(wǎng)絡(luò)請求這塊兒芙盘,一直用的ASIHttpRequest,但是這個開源項目好長時間不維護液兽。據(jù)說現(xiàn)在這塊兒都興用了AFNetwork了骂删,學(xué)習(xí)學(xué)習(xí),整理資料如下:
話說我學(xué)習(xí)那天(1.21)正值github被墻之日四啰,真糾結(jié)宁玫。所以文章最下面會擱一個AFNetwork的下載地址。ok,let’s go
1.首先要把AFNetwork導(dǎo)入到你的工程中 就是那19個文件afnetworking 文件夾
2.然后還要在工程里面引出2個新的framwork,SystemConfiguration和MobileCoreServices
3.很重要的一步在你的”YOURPROJECTNAME-Prefix.pch”文件里添加
#import
#import
基本上就是這樣子拟逮,然后你就可以使用了.你的工程需要什么功能就在你的class里面的頭文件添加什么功能的引用
如果你出現(xiàn)了下面AFNETWORKING的警告的話請重復(fù)安裝上面的
#else
#warning SystemConfiguration framework not found in project, or not included in precompiled header. Network reachability functionality will not be available.
#endif
#ifndef __UTTYPE__
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#warning MobileCoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.
#else
#warning CoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.
#endif
#endif
常用方法舉例:
1.較底層的一個封裝
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://httpbin.org/ip"]];
AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request];
operation.completionBlock = ^ {
NSLog(@"Complete: %@", operation.responseString);
};
[operation start];
2.基于上一個東東更高一層的封裝
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://httpbin.org/robots.txt"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure: %@", error);
}];
[operation start];
3.處理json請求
NSURL *url = [NSURL URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"App.net Global Stream: %@", JSON);
} failure:nil];
[operation start];
4.XML請求
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792%40N01&format=rest"]];
AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
XMLParser.delegate = self;
[XMLParser parse];
} failure:nil];
[operation start];
5.圖片請求:
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
6.圖片上傳處理撬统,監(jiān)測上傳狀態(tài):
NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id formData) {
[formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation start];
7.在線流媒體請求
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]];
operation.outputStream = [NSOutputStream outputStreamToMemory];
[operation start];
常見問題:
1. AFNetworking作用都有哪些?
NSURLConnection提供了+sendAsynchronousRequest:queue:completionHandler:和+sendAsynchronousRequest:queue:completionHandler: 敦迄,但是AFNetworking提供了更好的功能
*AFURLConnectionOperation和它的子類繼承NSOperation的恋追,允許請求被取消,暫停/恢復(fù)和由NSOperationQueue進行管理罚屋。
*AFURLConnectionOperation也可以讓你輕松得完成上傳和下載苦囱,處理驗證,監(jiān)控上傳和下載進度脾猛,控制的緩存撕彤。
*AFHTTPRequestOperation和它得子類可以基于http狀態(tài)和內(nèi)容列下來區(qū)分是否成功請求了
*AFNetworking可以將遠程媒體數(shù)據(jù)類型(NSData)轉(zhuǎn)化為可用的格式,比如如JSON猛拴,XML羹铅,圖像和plist。
*AFHTTPClient提供了一個方便的網(wǎng)絡(luò)交互接口愉昆,包括默認(rèn)頭职员,身份驗證,是否連接到網(wǎng)絡(luò)跛溉,批量處理操作焊切,查詢字符串參數(shù)序列化扮授,已經(jīng)多種表單請求
*的UIImageView+ AFNetworking增加了一個方便的方法來異步加載圖像。
2. AFNetworking是否支持緩存专肪?
可以刹勃,NSURLCache及其子類提供了很多高級接口用于處理緩存
如果你想將緩存存儲再磁盤,推薦使用SDURLCache
3.如何使用AFNetworking上傳一個文件嚎尤?
NSData *imageData = UIImagePNGRepresentation(image);
NSURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id formData) {
[formData appendPartWithFileData:imageData mimeType:@"image/png" name:@"avatar"];
}];
4.如何使用AFNetworking下載一個文件荔仁?
先創(chuàng)建一個AFURLConnectionOperation對象,然后再使用它的屬性outputStream進行處理
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:@"download.zip" append:NO];
5.如何解決:SystemConfiguration framework not found in project
請導(dǎo)入:
#import
#import
6.當(dāng)應(yīng)用程序退出時诺苹,如何保持持續(xù)的請求咕晋?
AFURLConnectionOperation有一個叫setShouldExecuteAsBackgroundTaskWithExpirationHandler:的方法用于處理在應(yīng)用程序進入后臺后,進行持續(xù)的請求
[self setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
}];