ios基础篇(三十)—— AFNetworking的使用

一、AFNetworking的创建

新建工程,命名为AFNDemo

二、导入AFNetworking.h

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

在ViewController.m中导入AFNetworking.h

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

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];
    
时间: 2024-08-08 22:07:29

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

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

UIToolBar存在于UINavigationController导航栏控制器中,而且默认被隐藏:设置UINavigationController的toolbarHidden属性可显示UIToolBar. 一.UIToolBar的设置 1.在RootViewController.m的viewDidLoad方法中添加代码: [self.navigationController setToolbarHidden:NO animated:YES]; 如图:显示底部ToolBar 2.设置UITool

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

一.Delegate Delegate本质是一种程序设计模型,iOS中使用Delegate主要用于两个页面之间的数据传递.iphone中常用@protocol和delegate的机制来实现接口的功能.例如想在A的功能要在B中实现,可以在A中定义一个Protocol. protocol用法: @interface ClassA :ClassB<protocol1, protocol2> 1.首先声明一个UIView类: @interface myView  :UIView{  } @end: 2

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

滚动视图(UIScrollView)通常用于显示内容尺寸大于屏幕尺寸的视图. 一.基本属性 1.CGSize contentSize :设置UIScrollView的滚动范围 2.CGPoint contentOffset :UIScrollView当前滚动的位置 3.UIEdgeInsets contentInset :设置内容的边缘 4.BOOL bounces 当超出边界时表示是否可以反弹 5.BOOL scrollEnabled 是否能滚动 6.BOOL showsHorizontalS

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

UINavigationController又被成为导航控制器,继承自UIViewController,以栈的方式管理所控制的视图控制器,下面就详细说一下UINavigationController的使用: 1.首先新建一个工程(就不多说了)创建RootViewController(继承自UIViewController). 2.打开AppDelegate.h文件添加属性 3.打开AppDelegate.m文件的 - (BOOL)application:(UIApplication *)appl

Python基础篇(三)

元组是序列的一种,与列表的区别是,元组是不能修改的. 元组一般是用圆括号括起来进行定义,如下: >>> (1,2,3)[1:2]     (2,) 如果元组中只有一个元素,元组的表示有些奇怪,末尾需要加上一个逗号: >>> (1,2,3)[1:2]     (2,) >>> 3*(3)      9      >>> 3*(3,)      (3, 3, 3) tuple函数 tuple函数用于将任意类型的序列转换为元组: >&

iOs基础篇(二十二)—— UIPickerView、UIDatePicker控件的使用

一.UIPickerView UIPickerView是一个选择器控件,可以生成单列的选择器,也可生成多列的选择器,而且开发者完全可以自定义选择项的外观,因此用法非常灵活. 1.常用属性 (1)numberOfComponents:获取UIPickerView指定列中包含的列表项的数量. (2)showsSelectionIndicator:控制是否显示UIPickerView中的选中标记(以高亮背景作为选中标记). 2.常见方法 (1)- (NSInteger)numberOfComponen

ios基础篇(二十)—— UIBezierPath绘制

UIBezierPath类可以创建基于矢量的路径,可以定义简单的形状,如椭圆或者矩形,或者有多个直线和曲线段组成的形状. 一.UIBezierPath使用: 1.创建path: 2.添加路径到path: 3.将path绘制出来: 1 //创建path 2 path = [UIBezierPath bezierPath]; 3 //添加路径 4 [path moveToPoint:(CGPoint){10,50}]; 5 [path addLineToPoint:(CGPoint){100,50}

.Net转Java自学之路—基础巩固篇三十二(JavaMail)

commons-fileupload组件: commons-fileupload.jar commons-io.jar 该组件会解析request中的上传数据,解析后的结果是一个表单项数据封装到一个FileItem对象中,只需调用FileItem中的方法即可. 上传三步:相关类 工厂:DisFileItemFactory 解析器:ServletFileUpload 表单项:FileItem //ServletFileUpload: setFileSizeMax(n*1024);//限制单个文件大

ios基础篇(二十七)—— Json解析

一.什么是Json JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C.C++.C#.Java.JavaScript.Perl.Python等).这些特性使JSON成为理想的数据交换语言. 易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率). 1.Json的语法规则 (1)数据在键值对中 (2)数据由逗号分隔 (3