iOS 网络 - AFNetworking 3.0

弃用的类
下面的类已从AFNetworking 3.0中废弃:
AFURLConnectionOperation
AFHTTPRequestOperation
AFHTTPRequestOperationManager

修改的类
下面的类包含基于NSURLConnection的API的内部实现。他们已经被使用NSURLSession重构:
UIImageView+AFNetworking
UIWebView+AFNetworking
UIButton+AFNetworking

一、使用步骤

1.创建下载任务

NSURLSessionConfiguration *configuration = [NSURLSessionConfigurationdefaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURLURLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequestrequestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nildestination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryURL = [[NSFileManagerdefaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nilcreate:NOerror:nil];
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];

2.创建上传任务

NSURLSessionConfiguration *configuration = [NSURLSessionConfigurationdefaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURLURLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequestrequestWithURL:URL];

NSURL *filePath = [NSURLfileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nilcompletionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"Success: %@%@", response, responseObject);
    }
}];
[uploadTask resume];

3.创建上传任务,多部分请求,带过程

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST"URLString:@"http://example.com/upload"parameters:nilconstructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURLfileURLWithPath:@"file://path/to/image.jpg"] name:@"file"fileName:@"filename.jpg"mimeType:@"image/jpeg"error:nil];
    } error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]];

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
              uploadTaskWithStreamedRequest:request
              progress:^(NSProgress * _Nonnull uploadProgress) {
                  // This is not called back on the main queue.// You are responsible for dispatching to the main queue for UI updatesdispatch_async(dispatch_get_main_queue(), ^{
                      //Update the progress view
                      [progressView setProgress:uploadProgress.fractionCompleted];
                  });
              }
              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                  if (error) {
                      NSLog(@"Error: %@", error);
                  } else {
                      NSLog(@"%@%@", response, responseObject);
                  }
              }];

[uploadTask resume];

4.创建数据任务

NSURLSessionConfiguration *configuration = [NSURLSessionConfigurationdefaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURLURLWithString:@"http://httpbin.org/get"];
NSURLRequest *request = [NSURLRequestrequestWithURL:URL];

NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"%@%@", response, responseObject);
    }
}];
[dataTask resume];

5.请求序列化

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 error:nil];
POST http://example.com/
Content-Type: application/x-www-form-urlencoded

foo=bar&baz[]=1&baz[]=2&baz[]=3
JSON Parameter Encoding

[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST"URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/json

{"foo": "bar", "baz": [1,2,3]}

6.通过AFNetworkReachabilityManager 可以用来检测网络状态的变化

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];

[[AFNetworkReachabilityManager sharedManager] startMonitoring];

7.响应序列化,JSON,XML和PLIST格式响应服务器数据

    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

8.使用AFHTTPSessionManager方法实现GET和POST请求

NSURL *URL = [NSURLURLWithString:@"http://example.com/resources/123.json"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:URL.absoluteString parameters:nilprogress:nilsuccess:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

9.利用AFNetworkActivityIndicatorManager显示加载提示

[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

10.使用AFImageResponseSerializer序列化图片数据

二、基本属性

三、代码示例

四、总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值