服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - IOS - iOS应用开发中AFNetworking库的常用HTTP操作方法小结

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

2021-01-19 15:22iOS开发网 IOS

AFNetworking库是Objective-C语言写成的用于处理HTTP的第三方库,在GitHub上开源并且一直在被更新和维护,下面就一起来看一下iOS应用开发中AFNetworking库的常用HTTP操作方法小结

准备
首先,你需要将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]}

 

延伸 · 阅读

精彩推荐
  • IOS关于iOS自适应cell行高的那些事儿

    关于iOS自适应cell行高的那些事儿

    这篇文章主要给大家介绍了关于iOS自适应cell行高的那些事儿,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    daisy6092021-05-17
  • IOSiOS布局渲染之UIView方法的调用时机详解

    iOS布局渲染之UIView方法的调用时机详解

    在你刚开始开发 iOS 应用时,最难避免或者是调试的就是和布局相关的问题,下面这篇文章主要给大家介绍了关于iOS布局渲染之UIView方法调用时机的相关资料...

    windtersharp7642021-05-04
  • IOSIOS开发之字典转字符串的实例详解

    IOS开发之字典转字符串的实例详解

    这篇文章主要介绍了IOS开发之字典转字符串的实例详解的相关资料,希望通过本文能帮助到大家,让大家掌握这样的方法,需要的朋友可以参考下...

    苦练内功5832021-04-01
  • IOSiOS中tableview 两级cell的展开与收回的示例代码

    iOS中tableview 两级cell的展开与收回的示例代码

    本篇文章主要介绍了iOS中tableview 两级cell的展开与收回的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    J_Kang3862021-04-22
  • IOSiOS 雷达效果实例详解

    iOS 雷达效果实例详解

    这篇文章主要介绍了iOS 雷达效果实例详解的相关资料,需要的朋友可以参考下...

    SimpleWorld11022021-01-28
  • IOSiOS通过逆向理解Block的内存模型

    iOS通过逆向理解Block的内存模型

    自从对 iOS 的逆向初窥门径后,我也经常通过它来分析一些比较大的应用,参考一下这些应用中某些功能的实现。这个探索的过程乐趣多多,不仅能满足自...

    Swiftyper12832021-03-03
  • IOSIOS 屏幕适配方案实现缩放window的示例代码

    IOS 屏幕适配方案实现缩放window的示例代码

    这篇文章主要介绍了IOS 屏幕适配方案实现缩放window的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要...

    xiari5772021-06-01
  • IOS解析iOS开发中的FirstResponder第一响应对象

    解析iOS开发中的FirstResponder第一响应对象

    这篇文章主要介绍了解析iOS开发中的FirstResponder第一响应对象,包括View的FirstResponder的释放问题,需要的朋友可以参考下...

    一片枫叶4662020-12-25