服务器之家

服务器之家 > 正文

iOS应用开发中AFNetworking库的常用HTTP操作方法小结

时间:2021-01-19 15:22     来源/作者:iOS开发网

准备
首先,你需要将afnetworking 框架包含到工程中。如果你还没有afnetworking的话,在这里下载最新的版本:
https://github.com/afnetworking/afnetworking
当你解压出下载的文件后,你将看到其中有一个afnetworking子文件夹,里面全是.h 和 .m 文件, 如下高亮显示的:

iOS应用开发中AFNetworking库的常用HTTP操作方法小结

将afnetworking拖拽到xcode工程中.

iOS应用开发中AFNetworking库的常用HTTP操作方法小结

当出现了添加文件的选项时,确保勾选上copy items into destination group's folder (if needed) 和 create groups for any added folders.
将afnetworking添加到预编译头文件,意味着这个框架会被自动的添加到工程的所有源代码文件中。

常用方法介绍
方法一: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<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);
}];


方法四:创建一个下载文件任务

复制代码 代码如下:


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


方法五:创建一个上传文件任务

复制代码 代码如下:


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


方法六:创建一个上传文件任务并显示进度

复制代码 代码如下:


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


方法七:创建一个上传数据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];


方法八:获取网络状态

复制代码 代码如下:

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


方法十二:获取请求的一些信息(我也没有用过,不太常用)

复制代码 代码如下:


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

 

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
返回顶部