關于AFNetWorking的一些理解

AFNetwork是一個輕量級的網絡請求api類庫。是以NSURLConnection, NSOperation和其他方法為基礎的。

下面這個例子是用來處理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];

使用方法:

1.下載AFNetwork,點擊下載

2.將文件夾名稱為AFNetworking拖入到你的工程項目即可

常見問題:

1. AFNetworking作用都有哪些?

NSURLConnection提供了+sendAsynchronousRequest:queue:completionHandler:和+sendAsynchronousRequest:queue:completionHandler: ,但是AFNetworking提供了更好的功能

*AFURLConnectionOperation和它的子類繼承NSOperation的,允許請求被取消,暫停/恢復和由NSOperationQueue進行管理。

*AFURLConnectionOperation也可以讓你輕松得完成上傳和下載,處理驗證,監控上傳和下載進度,控制的緩存。

*AFHTTPRequestOperation和它得子類可以基于http狀態和內容列下來區分是否成功請求了

*AFNetworking可以將遠程媒體數據類型(NSData)轉化為可用的格式,比如如JSON,XML,圖像和plist。

*AFHTTPClient提供了一個方便的網絡交互接口,包括默認頭,身份驗證,是否連接到網絡,批量處理操作,查詢字符串參數序列化,已經多種表單請求

*的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下載一個文件?

先創建一個AFURLConnectionOperation對象,然后再使用它的屬性outputStream進行處理

operation.outputStream = [NSOutputStream outputStreamToFileAtPath:@"download.zip" append:NO];

5.如何解決:SystemConfiguration framework not found in project

請導入:

#import

#import

6.當應用程序退出時,如何保持持續的請求?

AFURLConnectionOperation有一個叫setShouldExecuteAsBackgroundTaskWithExpirationHandler:的方法用于處理在應用程序進入后臺后,進行持續的請求

[self setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{

}];

一些實例:

1.XML 請求

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792@N01&format=rest"]];

AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {

XMLParser.delegate = self;

[XMLParser parse];

} failure:nil];

[operation start];

2.圖片請求:

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"]];

3.圖片上傳處理,監測上傳狀態:

didiwei? 17:28:57

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];

4.在線流媒體請求

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];


這幾天在評論頁面的時候發現get請求后加入2個以上的漢字會出現BadURL提示,斷點調試發現是多中文字符惹的禍,所以在URL使用以前先轉碼成UTF-8即可

這里順便說明下自己使用AFNetworking 的常用方法。

目前我只是用到

#import “AFHTTPClient.h”;

#import “AFHTTPRequestOperation.h”

這兩個類

發起一個請求


NSString *URLTmp =@”http://www.coneboy.com”;

NSString *URLTmp1 = [URLTmpstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //轉碼成UTF-8? 否則可能會出現錯誤

URLTmp = URLTmp1;

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURLURLWithString: URLTmp]];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation*operation, id responseObject) {

NSLog(@"Success: %@", operation.responseString);

NSString *requestTmp = [NSStringstringWithString:operation.responseString];

NSData *resData = [[NSData alloc] initWithData:[requestTmpdataUsingEncoding:NSUTF8StringEncoding]];

//系統自帶JSON解析

NSDictionary *resultDic = [NSJSONSerializationJSONObjectWithData:resData options:NSJSONReadingMutableLeaveserror:nil];

} failure:^(AFHTTPRequestOperation *operation, NSError *error){

NSLog(@”Failure: %@”, error);

[SVProgressHUD dismissWithError:@"提交失敗,請重試"];

}];

[operation start];

}

AFNetworking 下載圖片

AFNETWorking 下載圖片是異步并且可緩存到cache里面非常好用不會阻塞主線程。用過的都說好!而且使用也簡單!

#import “UIImageView+AFNetworking.h”


下面有關于自己的一些看法,AFNetWorking和NSData的區別一點是:

AFNetWorking是將遠程媒體數據類型(NSData)轉化為可用的格式,比如如JSON,XML,圖像和plist。

利用NSData 相關方法可以直接獲取到遠程媒體數據類型。不需要利用block回調拿取數據。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 搞了兩年多iOS開發了,網絡請求這塊兒,一直用的ASIHttpRequest,但是這個開源項目好長時間不維護。據說...
    oneDemo閱讀 492評論 0 1
  • iOS開發系列--網絡開發 概覽 大部分應用程序都或多或少會牽扯到網絡開發,例如說新浪微博、微信等,這些應用本身可...
    lichengjin閱讀 3,721評論 2 7
  • 現在大家都喜歡用AFNetworking,因為有人維護。看來一下官方文檔,把使用的代碼簡單羅列一下: 首先通過Co...
    隔壁班小明閱讀 828評論 0 0
  • 這是一篇團隊的成員之一斯科特·舍伍德所寫的教程,它是專門從事混合定位解決方案的動態加載的定位軟件公司。 網絡——你...
    隨風飄蕩的小逗逼閱讀 2,141評論 1 1
  • 在蘋果徹底棄用NSURLConnection之后自己總結的一個網上的內容,加上自己寫的小Demo,很多都是借鑒網絡...
    付寒宇閱讀 4,311評論 2 13