您当前的位置: 首页 >  网络

white camel

暂无认证

  • 1浏览

    0关注

    442博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

iOS开发网络篇 一一 AFN的基本使用

white camel 发布时间:2018-01-05 18:10:43 ,浏览量:1

一、AFN发送网络请求

知识点:

1. 使用AFN来发送网络请求: 需要创建会话管理者: AFHTTPSessionManager 对象

[AFHTTPSessionManager manager] 这个方法不是一个单例.

2. 请求路径中不能包含参数. GET请求的参数保存到一个字典中.

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

@interface ViewController ()

@end

@implementation ViewController

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self post];
}

- (void)get
{
    //1. 创建会话管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // http://localhost:8080/MJServer/login?username=123&pwd=123&method=get&type=JSON
    //2. 发送GET请求
    /*
     param1: 请求路径(不包含参数) NSString类型
     param2: 字典(发送给服务器的数据~参数)
     param3: progress 进度回调
     param4: success 请求成功回调
     task: 请求任务
     responseObject: 响应体信息(JSON-->OC对象)
     param5: failure 请求失败回调
     error: 错误信息
     响应体: task.response
     */
    // 创建字典
    NSDictionary *dict = @{
                           @"username" : @"zy",
                           @"pwd" : @"zy",
                           @"type" : @"JSON"
                           };
    [manager GET:@"http://localhost:8080/MJServer/login" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"%@---%@",[responseObject class],responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败--%@",error);
    }];
}

- (void)post
{
    //1. 创建会话管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2. 发送GET请求
    // 创建字典
    NSDictionary *dict = @{
                           @"username" : @"zy",
                           @"pwd" : @"zy",
                           @"type" : @"JSON"
                           };
    [manager POST:@"http://localhost:8080/MJServer/login" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"%@---%@",[responseObject class],responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败--%@",error);
    }];
}

@end

二、使用AFN实现文件下载

知识点: 

1. 会话管理者对象 manager 调用 downloadTaskWithRequest 方法来创建下载任务.

2. progress 块中的 NSProgress中的 completedUnitCount、totalUnitCount属性,来计算下载进度

3. destination 块中 需要返回NSURL对象, 并且内部已经默认作了剪切操作(临时数据 剪切到 文件指定位置)

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

@interface ViewController ()

@end

@implementation ViewController

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self download];
}

- (void)download
{
    //1. 创建会话管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2. 确定请求对象
    NSURL *url = [NSURL URLWithString:@"http://flv2.bn.netease.com/videolib3/1604/28/fVobI0704/SD/fVobI0704-mobile.mp4"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //3. 下载文件
    /*
     param1: 请求对象
     param2: progress 进度回调 downloadProgress
     
     param3: destination回调 (目标位置)
        有返回值
        targetPath:临时文件的路径(相当于Location)
        response: 响应头信息
     
     param4: completionHanler 下载完之后的回调
        filePath: 最终文件的下载路径
     */
    
    NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        // 下载进度
        NSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        // 内部已经 默认做了剪切操作(临时数据 剪切 到文件指定位置)
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:response.suggestedFilename];
        
        NSLog(@"targetPath--%@",targetPath);
        NSLog(@"fullPath--%@",fullPath);
        return [NSURL fileURLWithPath:fullPath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        NSLog(@"filePath--%@",filePath);
        
    }];
    
    //4. 执行task
    [download resume];
    
}
@end
三、AFN实现文件上传(POST请求)

使用方法:

[manager POST: parameters: constructingBodyWithBlock: progress: success: failure:
    //1. 创建会话管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //2. 发送post请求上传文件
    /*
     第一个参数:请求路径
     第二个参数:字典(非文件参数)可以传nil
     第三个参数:constructingBodyWithBlock 处理要上传的文件数据
     第四个参数:进度回调
     第五个参数:成功回调 responseObject:响应体信息
     第六个参数:失败回调
     */
    
    [manager POST:@"http://localhost:8080/MJServer/upload" parameters:nil constructingBodyWithBlock:^(id  _Nonnull formData) {
        
        UIImage *image = [UIImage imageNamed:@"love"];
        NSData *imageData = UIImageJPEGRepresentation(image, 0);
        // 使用formData来拼接数据
        /*
         param1: 二进制数据 要上传的文件参数
         param2: 服务器规定的
         param3: 该文件上传到服务器以什么名称保存
         */
        // [formData appendPartWithFileData:imageData name:@"file" fileName:@"zy.jpg" mimeType:@"image/jpg"];
        
        // [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/sunny/Desktop/photo/me.jpg"] name:@"file" fileName:@"zy.jpg" mimeType:@"image/jpg" error:nil];
        
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/sunny/Desktop/photo/me.jpg"] name:@"file" error:nil];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"上传成功---%@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"上传失败---%@",error);
        
    }];

关注
打赏
1661428283
查看更多评论
立即登录/注册

微信扫码登录

0.0547s