AFNetworking的一些解析

現在大家都喜歡用AFNetworking,因為有人維護??磥硪幌鹿俜轿臋n,把使用的代碼簡單羅列一下:

首先通過Cocoapos把AFNetworking拉下來

Podfile

platform :ios, '7.0'

pod "AFNetworking", "~> 2.0"

方法一:GET 請求

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {? ? NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {? ? NSLog(@"Error: %@", error);}];

方法二:POST 請求

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];NSDictionary *parameters = @{@"foo": @"bar"};[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {? ? NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {? ? NSLog(@"Error: %@", error);}];

方法三:POST Multi-Part Request

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];NSDictionary *parameters = @{@"foo": @"bar"};NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id formData) {? ? [formData appendPartWithFileURL:filePath name:@"image" error:nil];} success:^(AFHTTPRequestOperation *operation, id responseObject) {? ? NSLog(@"Success: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {? ? NSLog(@"Error: %@", error);}];

方法四:創(chuàng)建一個下載文件任務

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];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);}];[downloadTask resume];

方法五:創(chuàng)建一個上傳文件任務

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {? ? if (error) {? ? ? ? NSLog(@"Error: %@", error);? ? } else {? ? ? ? NSLog(@"Success: %@ %@", response, responseObject);? ? }}];[uploadTask resume];

方法六:創(chuàng)建一個上傳文件任務并顯示進度

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) {? ? ? ? [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] 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];

方法七:創(chuàng)建一個上傳數據data任務

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {? ? if (error) {? ? ? ? NSLog(@"Error: %@", error);? ? } else {? ? ? ? NSLog(@"%@ %@", response, responseObject);? ? }}];[dataTask resume];

方法八:獲取網絡狀態(tài)

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));

}];

方法九: HTTP Manager Reachability

NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];NSOperationQueue *operationQueue = manager.operationQueue;[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {? ? switch (status) {? ? ? ? case AFNetworkReachabilityStatusReachableViaWWAN:? ? ? ? case AFNetworkReachabilityStatusReachableViaWiFi:? ? ? ? ? ? [operationQueue setSuspended:NO];? ? ? ? ? ? break;? ? ? ? case AFNetworkReachabilityStatusNotReachable:? ? ? ? default:? ? ? ? ? ? [operationQueue setSuspended:YES];? ? ? ? ? ? break;? ? }}];[manager.reachabilityManager startMonitoring];

方法十:AFHTTPRequestOperation的GET請求

NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];op.responseSerializer = [AFJSONResponseSerializer serializer];[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {? ? NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {? ? NSLog(@"Error: %@", error);}];[[NSOperationQueue mainQueue] addOperation:op];

方法十一:Batch of Operations

NSMutableArray *mutableOperations = [NSMutableArray array];for (NSURL *fileURL in filesToUpload) {? ? NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) {? ? ? ? [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];? ? }];? ? AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];? ? [mutableOperations addObject:operation];}NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {? ? NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);} completionBlock:^(NSArray *operations) {? ? NSLog(@"All operations in batch complete");}];[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];

方法十二:獲取請求的一些信息(我也沒有用過,不太常用)

Request Serialization

Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.

NSString *URLString = @"http://example.com";NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};

Query String Parameter Encoding

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];

GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3

URL Form Parameter Encoding

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];POSThttp://example.com/Content-Type: application/x-www-form-urlencodedfoo=bar&baz[]=1&baz[]=2&baz[]=3

JSON Parameter Encoding

[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];POSThttp://example.com/Content-Type: application/json{"foo": "bar", "baz": [1,2,3]}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容