一、AFNetworking的创建

1、新建工程,命名为AFNDemo

2、导入AFNetworking.h

AFNetworking文件下载:https://github.com/AFNetworking/AFNetworking

在ViewController.m中导入AFNetworking.h

#import "ViewController.h"
#import "AFNetworking.h"

二、AFNetworking的使用

1、创建一个下载任务(官方网站上给出的例子)

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

2、创建一个上传任务

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

3、发送多个请求

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]]; NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}]; [uploadTask resume];

4、获取数据

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
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];

5、通过URL获取JSON数据

    NSString *str = [NSString stringWithFormat:@"http://192.168.199.245:88/json/b"];
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:url]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSString *html = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"Json:%@",html); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error:%@",error);
}]; [[NSOperationQueue mainQueue] addOperation:operation];

ios基础篇(三十)—— AFNetworking的使用的更多相关文章

  1. ios基础篇(十二)——UINavgationController的使用(三)ToolBar

    UIToolBar存在于UINavigationController导航栏控制器中,而且默认被隐藏:设置UINavigationController的toolbarHidden属性可显示UIToolB ...

  2. ios基础篇(十六)——UIWebView的基本使用

    UIWebView是内置的浏览器控件,可以用它来浏览网页.打开文档等.UIWebView是一个混合体,具体的功能控件内置的,实现一些基本的功能.UIWebView可以查看Html网页,pdf文件,do ...

  3. ios基础篇(十八)——Delegate 、NSNotification 和 KVO用法及其区别

    一.Delegate Delegate本质是一种程序设计模型,iOS中使用Delegate主要用于两个页面之间的数据传递.iphone中常用@protocol和delegate的机制来实现接口的功能. ...

  4. iOS基础篇(十五)——UIScrollView的基本用法

    滚动视图(UIScrollView)通常用于显示内容尺寸大于屏幕尺寸的视图. 一.基本属性 1.CGSize contentSize :设置UIScrollView的滚动范围 2.CGPoint co ...

  5. ioS基础篇(十九)——UIResponder简析

    UIResponder类定义了对象相应和控制事件的接口,他是UIApplication.UIView的超类,这类的实例通常被称为应答对象. 一.Responder对象 在iOS系统中,能够响应并处理事 ...

  6. ios基础篇(十四)——UITableView(二)属性及基本用法

    上一篇说了UITableView的重用机制,让我们对UITableView有了简单了解,下面说说UITableView的属性及常见方法. 一.属性 1.frame:设置控件的尺寸和大小 2.backg ...

  7. ios基础篇(十)——UINavgationController的使用(一)UIBarButtonItem的添加

    UINavigationController又被成为导航控制器,继承自UIViewController,以栈的方式管理所控制的视图控制器,下面就详细说一下UINavigationController的 ...

  8. Spring+SpringMVC+MyBatis+easyUI整合基础篇(十二)阶段总结

    不知不觉,已经到了基础篇的收尾阶段了,看着前面的十几篇文章,真的有点不敢相信,自己竟然真的坚持了下来,虽然过程中也有过懒散和焦虑,不过结果还是自己所希望的,克服了很多的问题,将自己的作品展现出来,也发 ...

  9. NIO相关基础篇三

    转载请注明原创出处,谢谢! 说在前面 上篇NIO相关基础篇二,主要介绍了文件锁.以及比较关键的Selector,本篇继续NIO相关话题内容,主要谈谈一些Linux 网络 I/O模型.零拷贝等一些内容, ...

  10. Hybrid APP基础篇(三)->Hybrid APP之Native和H5页面交互原理

    本文已经不维护,新地址: http://www.cnblogs.com/dailc/p/8097598.html 说明 Hybrid模式原生和H5交互原理 目录 前言 参考来源 前置技术要求 楔子 A ...

随机推荐

  1. java中的23中设计模式(转)

    设计模式(Design Patterns) --可复用面向对象软件的基础 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了 ...

  2. EditText光标颜色设置

    又一次做应用,发现EditText没有显示光标,借鉴了网上的方法,发现是因为光标是白色的,与背景一样造成的,这里记录一下如何设置EditText等的光标颜色: 需要在布局文件中指定androd:tex ...

  3. webapi aspose导出excel表格

    API 通过get请求,注意用到一个[FromUri]特性,使GET接收实体参数 /// <summary> /// 导出 /// </summary> /// <par ...

  4. 24-React Components组件

    Components 组件 1.组件 可以让UI独立的分割出来,可以让UI重复利用. 2.组件就像是JavaScript函数,它们能够接收任意的输入(称为"props",即属性)并 ...

  5. 没人能阻止你,除了你自己——Keep up the good work!

    今天在网上搜索一些关于计算机专业的论坛或者博客,于是发现了博客园,就进来了.我想把我的一些关于计算机科学与技术领域的学习经历纪录在此,以便于能和大家一起分享,一起努力,一起进步.说实话我是临床医学专业 ...

  6. Webpack参考资料

    学习是一种进步,只有不断的向别人学习,才能提升自己.三人行必有我师焉 1. http://www.cnblogs.com/zhengjialux/p/5861845.html

  7. React 高级指南小记

    接上篇,还是笔记,还是干货. 深入 JSX 如果使用 JSX 表达式 <Foo />,Foo 必须在范围内,因为这些标签被编译为对指定变量的直接引用. 由于 JSX 编译为对 React. ...

  8. Cocos2d-x 核心概念 - Node(节点)与Node层级架构

    Cocos2d-x采用层级结构管理场景 层 精灵 等节点(Node)对象 一个场景包含了多个层,一个层又包含多个对象 层级结构中的节点(Node)可以是场景,精灵等任何对象 节点的层级结构 Scene ...

  9. 调度系统任务创建---创建一个JoinTrigger的依赖任务(五)

    有时候我们需要创建一个任务,这个任务有多个下游任务,在所有下游任务执行成功后再触发一个join操作. 这种场景可以使用JoinTrigger的触发器来实现. 该场景对应的拓扑结构如下: 该触发器的详细 ...

  10. ANdroid URL

    1 Android开源项目和工具分类 http://blog.csdn.net/shimiso/article/details/40889361 2 分享45个android实例源码 http://w ...