一、AFNetworking的创建

1、新建工程,命名为AFNDemo

2、导入AFNetworking.h

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

在ViewController.m中导入AFNetworking.h

  1. #import "ViewController.h"
  2. #import "AFNetworking.h"

二、AFNetworking的使用

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

  1. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  2. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
  3.  
  4. NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
  5. NSURLRequest *request = [NSURLRequest requestWithURL:URL];
  6.  
  7. NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
  8. NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
  9. return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
  10. } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
  11. NSLog(@"File downloaded to: %@", filePath);
  12. }];
  13. [downloadTask resume];

2、创建一个上传任务

  1. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  2. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
  3.  
  4. NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
  5. NSURLRequest *request = [NSURLRequest requestWithURL:URL];
  6.  
  7. NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
  8. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  9. if (error) {
  10. NSLog(@"Error: %@", error);
  11. } else {
  12. NSLog(@"Success: %@ %@", response, responseObject);
  13. }
  14. }];
  15. [uploadTask resume];

3、发送多个请求

  1. NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  2. [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
  3. } error:nil];
  4.  
  5. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  6.  
  7. NSURLSessionUploadTask *uploadTask;
  8. uploadTask = [manager
  9. uploadTaskWithStreamedRequest:request
  10. progress:^(NSProgress * _Nonnull uploadProgress) {
  11. // This is not called back on the main queue.
  12. // You are responsible for dispatching to the main queue for UI updates
  13. dispatch_async(dispatch_get_main_queue(), ^{
  14. //Update the progress view
  15. [progressView setProgress:uploadProgress.fractionCompleted];
  16. });
  17. }
  18. completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
  19. if (error) {
  20. NSLog(@"Error: %@", error);
  21. } else {
  22. NSLog(@"%@ %@", response, responseObject);
  23. }
  24. }];
  25.  
  26. [uploadTask resume];

4、获取数据

  1. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  2. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
  3.  
  4. NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
  5. NSURLRequest *request = [NSURLRequest requestWithURL:URL];
  6.  
  7. NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  8. if (error) {
  9. NSLog(@"Error: %@", error);
  10. } else {
  11. NSLog(@"%@ %@", response, responseObject);
  12. }
  13. }];
  14. [dataTask resume];

5、通过URL获取JSON数据

  1. NSString *str = [NSString stringWithFormat:@"http://192.168.199.245:88/json/b"];
  2. NSURL *url = [NSURL URLWithString:str];
  3. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  4.  
  5. AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
  6. [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
  7.  
  8. NSString *html = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  9. NSLog(@"Json:%@",html);
  10.  
  11. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  12.  
  13. NSLog(@"Error:%@",error);
  14. }];
  15.  
  16. [[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. 课程设计 --- 黑白棋中的 AI

    原文链接:https://www.dreamwings.cn/reversi/3013.html 到了考试周了佯,可是偏偏这个时候迎来了很多很多的课程设计,幸好教授把C语言的课程设计提前发出了,不然都 ...

  2. Arduino学习经验(一)之解决舵机库和pwm输出冲突

    一.前言 最近在公司学习Arduino uno ,用它实现小车超声波避障功能.实现的功能很简单,就是在小车前方挂一个超声波模块,当碰到障碍物时,会通过舵机进行摆头,判断两边的距离,进行左右转弯.但是碰 ...

  3. SharePoint常用目录介绍

    SharePoint常用目录介绍 stsadm命令管理程序目录:C:\Program Files\Common Files\Microsoft Shared\web server extensions ...

  4. Swift高级语法学习总结(转)

    Swift高级语法学习总结 1.函数 1.1 func funcNmae()->(){} 这样就定义了一个函数,它的参数为空,返回值为空,如果有参数和返回值直接写在两个括号里就可以了 1.2 参 ...

  5. ASP.NET中cookie与Fiter实现简单登陆,AllowAnonymous匿名登陆

    向服务器发送cookie 在登陆的时候,我们可以可以通过下列代码,向服务器发送cookie,其中包括自己的账号信息(不涉及加密),用以后面判断访问者. HttpCookie cookie = new ...

  6. c# 无法加载 DLL xxxxxxxx找不到指定的模块。 (异常来自HRESULT:0x8007007E)。的一个解决方法

    最近在做一个程序,想把某些功能用C++写成DLL供C#调用.但是无法如何都无法调用,提示"无法加载 DLL xxxxxxxx找不到指定的模块. (异常来自HRESULT:0x8007007E ...

  7. ASP.NET MVC 提示there was error getting the type的解决方法

    在MVC中根据模型类创建控制器时提示there was error getting the type的原因是你新建的这个类模型文件后没有重新生成,先重新生成项目就可以添加控制器了.

  8. newInstance()和new()

    在Java开发特别是数据库开发中,经常会用到Class.forName( )这个方法.通过查询Java Documentation我们会发现使用Class.forName( )静态方法的目的是为了动态 ...

  9. python成长之路【第十一篇】:网络编程之线程threading模块

    一.threading模块介绍 threading 模块建立在 _thread 模块之上.thread 模块以低级.原始的方式来处理和控制线程,而 threading 模块通过对 thread 进行二 ...

  10. scss/css 中添加ie hack

    @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) { /* IE10+ specific styles ...