afnetwork使用

Usage

HTTP Request Operation Manager

AFHTTPRequestOperationManager encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management.

GET Request

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 URL-Form-Encoded Request

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<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

AFURLSessionManager

AFURLSessionManager creates and manages an NSURLSession object based on a specifiedNSURLSessionConfiguration object, which conforms to <NSURLSessionTaskDelegate>,<NSURLSessionDataDelegate><NSURLSessionDownloadDelegate>, and <NSURLSessionDelegate>.

Creating a Download Task

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

Creating an Upload Task

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

Creating an Upload Task for a Multi-Part Request, with Progress

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> 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];

Creating a Data Task

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

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];
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];
POST http://example.com/
Content-Type: application/json

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

Network Reachability Manager

AFNetworkReachabilityManager monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.

Network reachability is a diagnostic tool that can be used to understand why a request might have failed. It should not be used to determine whether or not to make a request.

Shared Network Reachability

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

Security Policy

AFSecurityPolicy evaluates server trust against pinned X.509 certificates and public keys over secure connections.

Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.

Allowing Invalid SSL Certificates

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production

AFHTTPRequestOperation

AFHTTPRequestOperation is a subclass of AFURLConnectionOperation for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.

Although AFHTTPRequestOperationManager is usually the best way to go about making requests,AFHTTPRequestOperation can be used by itself.

GET with AFHTTPRequestOperation

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<AFMultipartFormData> 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];
时间: 2024-11-06 02:37:46

afnetwork使用的相关文章

AFNetwork学习(二)——GET/POST请求

为了学习AFNetwork,自己搭建整理了一下AFNetwork向后台发送请求和后台返回json数据的整个处理过程.利用Struts2搭建了一个后台,提供Action并返回json数据 环境:Xcode6.3 后台:tomcat+myeclipse10.6  框架:struts2 1.新建一个single-view applicationproject名为IOS_AFNetwork,开发语言选择OC. 2.将AFNetwork库文件增加到project中,例如以下图: watermark/2/t

AFNetWork 请求https

AFNetWork这个库,是现在大家使用比较用的库,我们在做即时通讯的时候,也会加入这个库,用起来还是比较爽的. 有时候我们会用到https,在AFNetwork这个库,其实已经很好的封装了https,是的我们很简单就能使用. 第一步,导入AFNetWorking 库 第二步,在pch文件中加入 [objc] view plaincopy #import <SystemConfiguration/SystemConfiguration.h> #import <MobileCoreServ

AFNetwork 作用和用法详解

AFNetworking是一个轻量级的iOS网络通信类库.它建立在NSURLConnection和NSOperation等类库的基础上,让很多网络通信功能的实现变得十分简单.它支持HTTP请求和基于REST的网络服务(包括GET.POST. PUT.DELETE等).支持ARC. Github地址:https://github.com/AFNetworking/AFNetworking // // MJViewController.m // 03.AFN演练 // // Created by a

AFNetWork中使用https

AFNetWork这个库,是现在大家使用比较用的库,我们在做即时通讯的时候,也会加入这个库,用起来还是比较爽的. 有时候我们会用到https,在AFNetwork这个库,其实已经很好的封装了https,是的我们很简单就能使用. 第一步,导入AFNetWorking 库 第二步,在pch文件中加入 #import <SystemConfiguration/SystemConfiguration.h> #import <MobileCoreServices/MobileCoreService

AFNetwork 2.0在请求时报错code=-1016 和 3840

在进行网络请求时出现-1016 是因为只支持 text/json,application/json,text/javascript 你可以添加text/html 一劳永逸的方法是 在 AFURLResponseSerialization.h 里面搜索 self.acceptableContentTypes 然后 在里面 添加 @"text/html",@"text/plain" 这样就可以解决-1016的错误了 但是随之而来的是3840错误 Error Domain

第三方库AFNetwork的作用和用法详解

1>默认提交请求的数据是二进制的,返回格式是JSON 请求格式(manager.requestSerializer) AFHTTPRequestSerializer          二进制格式(NSData) AFJSONRequestSerializer          JSON AFPropertyListRequestSerializer  PList(是一种特殊的XML,解析起来相对容易) 返回格式(manager.responseSerializer) AFHTTPResponse

AFNetwork ATS 网络层改造

最近一直做项目的ATS改造,期间遇到了种种问题,各种坑都记录下来, 比如iOS版本.afnetwork版本.证书(是否为自签证书).域名验证.TLS版本等等,我们项目更复杂,还使用了域名到IP映射的路由表策略,在验证自签证书的时候各种配置host,这种需求在文章里就不赘述了,有相似需求的可以私下讨论: 有描述不对的地方,欢迎大神指正! 先鬼扯点儿小背景,不喜请略过黄色部分:) 关于ATS,简单说就是app使用的网络请求都必须走https,iOS9以后,此设置默认开启,项目中所有的http请求直接

iOS 文件下载 (AFNetwork 三方框架 文件名中文字符乱码问题解决)四

很久以前,就把这篇文章的andriod部分和服务器部分搞定,最近论文送审途中,于是写了几行简单的代码如下. 把AFNetwork拿来做一下.具体代码如下: -(void)download { NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] i

AFNetwork作用和用法详解

AFNetwork是一个轻量级的网络请求api类库.是以NSURLConnection, NSOperation和其他方法为基础的. 下面这个例子是用来处理json请求的:NSURL *url = [NSURL URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"];NSURLRequest *request = [NSURLRequest requestWithURL:url];AFJSONRe