iOS开发——AFNetworking框架使用详解

AFNetworking is a delightful networking library for iOS and Mac OS X.It’s built on top of the Foundation URL Loading System, extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.

AFNetworking是一个基于iOS和Mac OS X的而且备受人们喜爱的网络类库。它建立在URL 装载系统框架的顶层,内置在Cocoa里,扩展了强有力的高级网络抽象。拥有良好设计的模块架构和丰富的功能的它使用起来很愉悦。

下载链接:https://github.com/AFNetworking/AFNetworking

使用方法:

1.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);
}];

2.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);
}];

3.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);
}];

4.创建一个下载任务

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

5.创建一个上传任务

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

6.创建一个上传文件任务并显示进度

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

7.创建一个数据流任务

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

8.获取网络状态

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

[[AFNetworkReachabilityManager sharedManager] startMonitoring];

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

10.AFHTTPRequestOperation的GET请求(AFHTTPRequestOperationManager通常是最好的去请求的方式,但是AFHTTPRequestOpersion也能够单独使用)

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

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

以上就是AFNetworking中一些常用的方法,AFNetworking请求到数据后,自动对请求到的数据进行解析,iOS中数据请求这方面AFNetworking是一个用起来很不错的第三方库。

时间: 2024-08-28 18:06:51

iOS开发——AFNetworking框架使用详解的相关文章

【iOS开发必收藏】详解iOS应用程序内使用IAP/StoreKit付费、沙盒(SandBox)测试、创建测试账号流程!【2012-12-11日更新获取”产品付费数量等于0的问题”】

转的别人的 看到很多童鞋问到,为什么每次都返回数量等于0?? 其实有童鞋已经找到原因了,原因是你在 ItunesConnect 里的 “Contracts, Tax, and Banking”没有完成设置账户信息. 确定 ItunesConnect 里 “Contracts, Tax, and Banking”的状态,如下图所示,即可: 这里也是由于Himi疏忽的原因没有说明,这里先给童鞋们带来的麻烦,致以歉意. //——2012-6-25日更新iap恢复 看到很多童鞋说让Himi讲解如何恢复i

iOS开发之手势gesture详解(一)

前言 在iOS中,你可以使用系统内置的手势识别(GestureRecognizer),也可以创建自己的手势.GestureRecognizer将低级别的转换为高级别的执行行为,是你绑定到view的对象,当发生手势,绑定到的view对象会响应,它确定这个动作是否对应一个特定的手势(swipe,pinch,pan,rotation).如果它能识别这个手势,那么就会向绑定它的view发送消息,如下图 UIKit框架提供了一些预定义的GestureRecognizer.包含下列手势 UITapGestu

iOS开发摇动手势实现详解

1.当设备摇动时,系统会算出加速计的值,并告知是否发生了摇动手势.系统只会运动开始和结束时通知你,并不会在运动发生的整个过程中始终向你报告每一次运动.例如,你快速摇动设备三次,那只会收到一个摇动事件. 2,想要实现摇动手势,首先需要使视图控制器成为第一响应者,注意不是单独的控件.成为第一响应者最恰当的时机是在视图出现的时候,而在视图消失的时候释放第一响应者. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 -(BOOL)canBecomeFirstRespond

iOS开发之手势gesture详解(二)

与其他用户界面控件交互 UIControl子类会覆盖parentView的gesture.例如当用户点击UIButton时,UIButton会接受触摸事件,它的parentView不会接收到.这仅适用于手势识别重叠的默认动作的控制,其中包括: 一根手指单击动作:UIButton, UISwitch, UIStepper, UISegmentedControl, and UIPageControl. 一根手指擦碰动作:UISlider 一根手指拖动动作:UISwitch 包含多点触摸的事件 在iO

iOS开发——UI篇&amp;ScrollView详解

ScrollView详解 创建方式 1:StoryBoard/Xib 这里StoarBoard就不多说,直接拖就可以,说太多没意思,如果连这个都不会我只能先给你跪了! 2:代码: CGRect bounds = [ [ UIScreen mainScreen ] applicationFrame ] ; UIScrollView* scrollView = [ [UIScrollView alloc ] initWithFrame:bounds ]; 当你创建完滚动视图后,你可以将另一个视图的内

iOS开发——UIView与CALayer详解

UIView与CALayer详解 研究Core Animation已经有段时间了,关于Core Animation,网上没什么好的介绍.苹果网站上有篇专门的总结性介绍,但是似乎原理性的东西不多,看得人云山雾罩,感觉,写那篇东西的人,其实是假 设读的人了解界面动画技术的原理的.今天有点别的事情要使用Linux,忘掉了ssh的密码,没办法重新设ssh,结果怎么也想不起来怎么设ssh远程登 陆了,没办法又到网上查了一遍,太浪费时间了,痛感忘记记笔记是多么可怕的事情.鉴于Core Animation的内

iOS开发-语法篇-block详解

一:基本定义 /*初步上式block定义的一些理解和解释,接下来会详解: *block名为myBlock,结合C的函数指针,myBlock为block体的指针,指向block体的入口地址 *int result = myBlock(5) <==> ^(int num){return num*num}(5)//将5传给num *回调时可以将myBlock作为参数传入,也可以直接传入block体^(int num){…};// *整个block体作为参数传入时,往往没有参数,只是进行延迟运算作用,

IOS开发之关键字category详解

什么是Category Category模式用于向已经存在的类添加方法从而达到扩展已有类的目的,在很多情形下Category也是比创建子类更优的选择.新添加的方法 同样也会被被扩展的类的所有子类自动继承.当知道已有类中某个方法有BUG,但是这个类是以库的形式存在的,我们无法直接修改源代码的时 候,Category也可以用于替代这个已有类中某个方法的实体,从而达到修复BUG的目的.然而却没有什么便捷的途径可以去调用已有类中原有的那个被替 换掉方法实体了.需要注意的是,当准备有Category来替换

iOS开发——深拷贝与浅拷贝详解

深拷贝和浅拷贝这个问题在面试中常常被问到,而在实际开发中,只要稍有不慎,就会在这里出现问题.尤其对于初学者来说,我们有必要来好好研究下这个概念.我会以实际代码来演示,相关示例代码上传至 这里 . 首先通过一句话来解释:深拷贝就是内容拷贝,浅拷贝就是指针拷贝. 深拷贝就是拷贝出和原来仅仅是值一样,但是内存地址完全不一样的新的对象,创建后和原对象没有任何关系.浅拷贝就是拷贝指向原来对象的指针,使原对象的引用计数+1,可以理解为创建了一个指向原对象的新指针而已,并没有创建一个全新的对象. (1)非容器