iOS网络编程————AFNetworking上传和下载

作为使用最广泛的网络第三方框架,AFNetworking2.0对最新的iOS特性有很好的支持,对NSURL进行了封装,使用更加简便,功能更加完善。


导入AFNetworking

1:Github下载地址:https://github.com/AFNetworking/AFNetworking

2:将AFNetworking和UIKit+AFNetworking拖入当前的工程中,iOS7之后对网络的访问要另加设置,不要忘记开启网络(info.plist中添加App Transport Security Settings,在其下添加Allow Arbitrary Loads并设置其value为YES)


另种方法:在终端利用cocoaPods来将AFNetworking配置到当前工程中

1:终端输入:pod search AFNetworking并拷贝

2:cd到当前工程目录

3:初始化cocoa环境:pod init  (会自动创建Podfile文件)

4:编辑Podfile文件:vim Podfile

5:在终端中输入i,表示插入内容到Podfile

6:在target ‘工程名’ do与end之间写入拷贝的AFNetworking库

7:输入完以后,按下Esc键退出编辑状态,然后输入:wq,保存并退出。

8:在Finder中打开工程目录,在.xcworkspace中进行下面的编辑任务即可。

使用AFNetworking实现基本的下载数据任务

#import "ViewController.h"
#import "AFNetworking.h"
#import "UIProgressView+AFNetworking.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

//downloadButton控制下载的方法
- (IBAction)downloadTask:(id)sender {
    
    //记住这个套路!!!
    
    //下载地址
    NSString *urlString = @"http://218.76.27.57:8080/chinaschool_rs02/135275/153903/160861/160867/1370744550357.mp3";
    //创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    
    //创建会话管理对象(在不使用Configuration来设置时用默认的manager足矣)
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    
    //创建下载任务
    NSURLSessionDownloadTask *downloadTask = [sessionManager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress) {
        
        //progressView和progressLabel同步进度
        _progressView.observedProgress = downloadProgress;
        
        NSString *progressString = [NSString stringWithFormat:@"%.1f%%", downloadProgress.completedUnitCount * 1.0 / downloadProgress.totalUnitCount * 100];
        
        [_progressLabel performSelectorOnMainThread:@selector(setText:) withObject:progressString waitUntilDone:YES];
        
    
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        //接收到响应,准备开始接受数据
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        
        //打印请求状态码
        NSLog(@"状态码:%li", httpResponse.statusCode);
        
        //targetPath临时问价保存路径
        
        //返回值为本次下载任务的保存路径
        NSString *filePath1 = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/菊花台.mp3"];
        
        //此block返回值为下载完之后文件存放的路径
        //这个返回的NSURL后面会传到filePath,因此这里自己设置的filePath可以随意取名
        return [NSURL fileURLWithPath:filePath1];
        
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        //这个block返回的filePath实际上就是我们上面给他的确定的filePath,在这里他提供了这个可查下载文件路径的参数
        NSLog(@"下载完成路径:%@", filePath);
    }];
    
    //开始任务
    [downloadTask resume];
    
    //设置progressView的进度
//    [_progressView setProgressWithDownloadProgressOfTask:downloadTask animated:YES];
}


使用AFNetworking实现基础的上传任务(本地上传图片和文字到新浪微博,新浪微博的用户token和发布微博消息的api已拿到)

#import "AFNetworking.h"
#import "UIKit+AFNetworking.h"
#import "UIProgressView+AFNetworking.h"
#import "ViewController.h"

@class AFHTTPSessionManager;

@interface ViewController () 

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;



@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}





- (IBAction)uploadTask:(id)sender {
    
    if (_textField.text.length == 0) {
        return;
    }
    
    //上传路径
    NSString *urlString = @"https://api.weibo.com/2/statuses/upload.json";
    //登录认证
    NSString *token = @"2.00hd363CtKpsnBedca9b3f35tBYiPD";
    
    //拼接参数列表
    NSDictionary *dic = @{@"access_token" : token, @"status" : _textField.text};
    
    //创建manager
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    
    //创建上传方法
    NSURLSessionDataTask *dataTask = [sessionManager POST:urlString parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //本地文件路径
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"gem" ofType:@"jpeg"];
        
        NSData *imageData = [NSData dataWithContentsOfFile:filePath];
        
        //添加上传的数据
        [formData appendPartWithFileData:imageData name:@"pic" fileName:@"gem.jpeg" mimeType:@"image/jpeg"];
        
        //新版本AFNetworking提供了progress的参数
    } progress: ^(NSProgress * uploadProgress){
        

        NSLog(@"%@", uploadProgress);
        
        //progressLabel和progressView同步显示进程
        NSString *labelString = [NSString stringWithFormat:@"%.1f%%", (CGFloat)uploadProgress.completedUnitCount / uploadProgress.totalUnitCount * 100];
        
        [_progressLabel performSelectorOnMainThread:@selector(setText:) withObject:labelString waitUntilDone:YES];
        
        _progressView.observedProgress = uploadProgress;
        
    }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"上传成功:%@", responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"上传失败:%@",error);

    }];
    

    
//    [_progressView setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)dataTask animated:YES];
    
}



你可能感兴趣的:(网络编程,AFNetworking,CocoaPods)