网络请求AFNetworking使用(一)

1 使用cocoa pod引入AFNetworking,#imoport<AFNetworking/AFNetworking.h>

2 使用方法

(1)get请求

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];[manager ^(AFHTTPRequestOperation *operation, id responseObject) {NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {NSLog(@"Error: %@", error);}];

(2)post请求

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];NSDictionary *parameters = @{@"foo": @"bar"};[manager parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {NSLog(@"Error: %@", error);}];

(3)图片上传

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];NSDictionary *parameters = @{@"foo": @"bar"};file://path/to/image.png"];[manager parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {[formData ];} success:^(AFHTTPRequestOperation *operation, id responseObject) {NSLog(@"Success: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {NSLog(@"Error: %@", error);}];

(4)文件下载

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];^NSURL *(NSURL *targetPath, NSURLResponse *response) {];return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {NSLog(@"File downloaded to: %@", filePath);}];[downloadTask resume];

(5)创建上传任务

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];file://path/to/image.png"];^(NSURLResponse *response, id responseObject, NSError *error) {if (error) {NSLog(@"Error: %@", error);} else {, response, responseObject);}}];[uploadTask resume];

(6)带进度的任务上传

^(id<AFMultipartFormData> formData) {[formData file://path/to/image.jpgfilename.jpgimage/jpeg];} 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 {, response, responseObject);}}];[uploadTask resume];

3其他使用方法见AFNetworking

版权声明:本文为博主原创文章,未经博主允许不得转载。

,世界会向那些有目标和远见的人让路(冯两努——香港着名推销商

网络请求AFNetworking使用(一)

相关文章:

你感兴趣的文章:

标签云: