AFNetworking是一個討人喜歡的網絡庫,適用於iOS以及Mac OS X. 它構建於在NSURLConnection, NSOperation, 以及其餘熟悉的Foundation技術之上. 它擁有良好的架構,豐富的api,以及模塊化構建方式,使得使用起來很是輕鬆.例如,他可使用很輕鬆的方式從一個url來獲得json數據:php
1 |
NSURL *url = [NSURL URLWithString:@"http://api.twitter.com/1/statuses/public_timeline.json"]; |
2 |
NSURLRequest *request = [NSURLRequest requestWithURL:url]; |
3 |
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { |
4 |
NSLog(@"Public Timeline: %@", JSON); |
5 |
} failure:nil]; |
6 |
[operation start]; |
如何開始使用
綜述
CORE:
AFURLConnectionOperation:一個 NSOperation 實現了NSURLConnection 的代理方法.html
HTTP Requests:git
AFHTTPRequestOperation:AFURLConnectionOperation的子類,當request使用的協議爲HTTP和HTTPS時,它壓縮了用於決定request是否成功的狀態碼和內容類型.程序員
AFJSONRequestOperation:AFHTTPRequestOperation的一個子類,用於下載和處理jason response數據.github
AFXMLRequestOperation:AFHTTPRequestOperation的一個子類,用於下載和處理xml response數據.json
AFPropertyListRequestOperation:AFHTTPRequestOperation的一個子類,用於下載和處理property list response數據.api
HTTP CLIENT:
AFHTTPClient:捕獲一個基於http協議的網絡應用程序的公共交流模式.包含:xcode
- 使用基本的url相關路徑來只作request
- 爲request自動添加設置http headers.
- 使用http 基礎證書或者OAuth來驗證request
- 爲由client製做的requests管理一個NSOperationQueue
- 從NSDictionary生成一個查詢字符串或http bodies.
- 從request中構建多部件
- 自動的解析http response數據爲相應的表現數據
- 在網絡可達性測試用監控和響應變化.
IMAGES
AFImageRequestOperation:一個AFHTTPRequestOperation的子類,用於下載和處理圖片.緩存
UIImageView+AFNetworking:添加一些方法到UIImageView中,爲了從一個URL中異步加載遠程圖片服務器
例子程序
XML REQUEST
1 |
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"]]; |
2 |
AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) { |
3 |
XMLParser.delegate = self; |
4 |
[XMLParser parse]; |
5 |
} failure:nil]; |
6 |
[operation start]; |
IMAGE REQUEST
1 |
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)]; |
2 |
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]]; |
API CLIENT REQUEST
1 |
// AFGowallaAPIClient is a subclass of AFHTTPClient, which defines the base URL and default HTTP headers for NSURLRequests it creates |
2 |
[[AFGowallaAPIClient sharedClient] getPath:@"/spots/9223" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { |
3 |
NSLog(@"Name: %@", [responseObject valueForKeyPath:@"name"]); |
4 |
NSLog(@"Address: %@", [responseObject valueForKeyPath:@"address.street_address"]); |
5 |
} failure:nil]; |
FILE UPLOAD WITH PROGRESS CALLBACK
01 |
NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"]; |
02 |
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; |
03 |
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5); |
04 |
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) { |
05 |
[formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"]; |
06 |
}]; |
07 |
|
08 |
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease]; |
09 |
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { |
10 |
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite); |
11 |
}]; |
12 |
[operation start]; |
STREAMING REQUEST
1 |
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]]; |
2 |
|
3 |
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease]; |
4 |
operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]]; |
5 |
operation.outputStream = [NSOutputStream outputStreamToMemory]; |
6 |
[operation start]; |
此文章是基於AFNetworking2.5版本的,須要看AFNetworking2.0版本的請看上一篇文章:AFNetworking2.0使用
1.檢測網絡狀態
- + (void)netWorkStatus
- {
-
-
- [[AFNetworkReachabilityManager sharedManager] startMonitoring];
-
-
- [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
- NSLog(@"%ld", status);
- }];
- }
2.JSON方式獲取數據
- + (void)JSONDataWithUrl:(NSString *)url success:(void (^)(id json))success fail:(void (^)())fail;
- {
- AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
-
- NSDictionary *dict = @{@"format": @"json"};
-
- [manager GET:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
- if (success) {
- success(responseObject);
- }
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- NSLog(@"%@", error);
- if (fail) {
- fail();
- }
- }];
- }
3.xml方式獲取數據
- + (void)XMLDataWithUrl:(NSString *)urlStr success:(void (^)(id xml))success fail:(void (^)())fail
- {
- AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
-
-
- manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
-
- NSDictionary *dict = @{@"format": @"xml"};
-
-
- [manager GET:urlStr parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
- if (success) {
- success(responseObject);
- }
-
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- NSLog(@"%@", error);
- if (fail) {
- fail();
- }
- }];
- }
4.post提交json數據
- + (void)postJSONWithUrl:(NSString *)urlStr parameters:(id)parameters success:(void (^)(id responseObject))success fail:(void (^)())fail
- {
- AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
-
- manager.requestSerializer = [AFJSONRequestSerializer serializer];
-
- manager.responseSerializer = [AFHTTPResponseSerializer serializer];
- [manager POST:urlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
- if (success) {
- success(responseObject);
- }
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- NSLog(@"%@", error);
- if (fail) {
- fail();
- }
- }];
-
- }
5.下載文件
- + (void)sessionDownloadWithUrl:(NSString *)urlStr success:(void (^)(NSURL *fileURL))success fail:(void (^)())fail
- {
- NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
- AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
-
- NSString *urlString = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
-
- NSURL *url = [NSURL URLWithString:urlString];
- NSURLRequest *request = [NSURLRequest requestWithURL:url];
-
- NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
-
-
-
- NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
- NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];
-
-
- NSURL *fileURL = [NSURL fileURLWithPath:path];
-
- if (success) {
- success(fileURL);
- }
-
- return fileURL;
- } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
- NSLog(@"%@ %@", filePath, error);
- if (fail) {
- fail();
- }
- }];
-
- [task resume];
- }
6.文件上傳-自定義上傳文件名
- + (void)postUploadWithUrl:(NSString *)urlStr fileUrl:(NSURL *)fileURL fileName:(NSString *)fileName fileType:(NSString *)fileTye success:(void (^)(id responseObject))success fail:(void (^)())fail
- {
-
- AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
- manager.responseSerializer = [AFHTTPResponseSerializer serializer];
-
- [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
-
-
-
-
-
-
-
- [formData appendPartWithFileURL:fileURL name:@"uploadFile" fileName:fileName mimeType:fileTye error:NULL];
-
- } success:^(AFHTTPRequestOperation *operation, id responseObject) {
- if (success) {
- success(responseObject);
- }
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- if (fail) {
- fail();
- }
- }];
- }
7.文件上傳-隨機生成文件名
- + (void)postUploadWithUrl:(NSString *)urlStr fileUrl:(NSURL *)fileURL success:(void (^)(id responseObject))success fail:(void (^)())fail
- {
- AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
-
-
-
-
-
- manager.responseSerializer = [AFHTTPResponseSerializer serializer];
-
-
- [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
-
-
-
- [formData appendPartWithFileURL:fileURL name:@"uploadFile" error:NULL];
- } success:^(AFHTTPRequestOperation *operation, id responseObject) {
- if (success) {
- success(responseObject);
- }
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- NSLog(@"錯誤 %@", error.localizedDescription);
- if (fail) {
- fail();
- }
- }];
- }