当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS应用开发中AFNetworking库的常用HTTP操作方法小结

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

2019年07月24日  | 移动技术网IT编程  | 我要评论

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

2016516152538410.jpg (238×500)

将afnetworking拖拽到xcode工程中.

2016516152554241.jpg (700×474)

当出现了添加文件的选项时,确保勾选上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 uicollectionview实现横向滚动

    现在使用卡片效果的app很多,之前公司让实现一种卡片效果,就写了一篇关于实现卡片的文章。文章最后附有demo实现上我选择了使用uicollectionview ... [阅读全文]
  • iOS UICollectionView实现横向滑动

    本文实例为大家分享了ios uicollectionview实现横向滑动的具体代码,供大家参考,具体内容如下uicollectionview的横向滚动,目前我使... [阅读全文]
  • iOS13适配深色模式(Dark Mode)的实现

    iOS13适配深色模式(Dark Mode)的实现

    好像大概也许是一年前, mac os系统发布了深色模式外观, 看着挺刺激, 时至今日用着也还挺爽的终于, 随着iphone11等新手机的发售, ios 13系统... [阅读全文]
  • ios 使用xcode11 新建项目工程的步骤详解

    ios 使用xcode11 新建项目工程的步骤详解

    xcode11新建项目工程,新增了scenedelegate这个类,转而将原appdelegate负责的对ui生命周期的处理担子接了过来。故此可以理解为:ios... [阅读全文]
  • iOS实现转盘效果

    本文实例为大家分享了ios实现转盘效果的具体代码,供大家参考,具体内容如下demo下载地址: ios转盘效果功能:实现了常用的ios转盘效果,轮盘抽奖效果的实现... [阅读全文]
  • iOS开发实现转盘功能

    本文实例为大家分享了ios实现转盘功能的具体代码,供大家参考,具体内容如下今天给同学们讲解一下一个转盘选号的功能,直接上代码直接看viewcontroller#... [阅读全文]
  • iOS实现轮盘动态效果

    本文实例为大家分享了ios实现轮盘动态效果的具体代码,供大家参考,具体内容如下一个常用的绘图,主要用来打分之类的动画,效果如下。主要是ios的绘图和动画,本来想... [阅读全文]
  • iOS实现九宫格连线手势解锁

    本文实例为大家分享了ios实现九宫格连线手势解锁的具体代码,供大家参考,具体内容如下demo下载地址:效果图:核心代码://// clockview.m// 手... [阅读全文]
  • iOS实现卡片堆叠效果

    本文实例为大家分享了ios实现卡片堆叠效果的具体代码,供大家参考,具体内容如下如图,这就是最终效果。去年安卓5.0发布的时候,当我看到安卓全新的material... [阅读全文]
  • iOS利用余弦函数实现卡片浏览工具

    iOS利用余弦函数实现卡片浏览工具

    本文实例为大家分享了ios利用余弦函数实现卡片浏览工具的具体代码,供大家参考,具体内容如下一、实现效果通过拖拽屏幕实现卡片移动,左右两侧的卡片随着拖动变小,中间... [阅读全文]
验证码:
移动技术网