zoukankan      html  css  js  c++  java
  • iOS- 利用AFNetworking3.0+(最新AFN)

    
    
    官方建议AFN的使用方法
     

    0.导入框架准备工作  

    •1. 将AFNetworking3.0+框架程序拖拽进项目
     
    •2. 或使用Cocopod 导入AFNetworking3.0+
     
    •3.  引入
    #import "AFNetworking.h"

    ---->

    1.UI准备工作  

    A. 定义一个全局的 NSURLSessionDownloadTask:下载管理句柄
       由其负责所有的网络操作请求
    @interface ViewController ()
    {
        // 下载句柄
        NSURLSessionDownloadTask *_downloadTask;
    }
    
    .h文件
    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController
    // 下载文件显示
    
    @property (weak, nonatomic) IBOutlet UIImageView *imageView;
    // 下载进度条显示
    
    @property (weak, nonatomic) IBOutlet UIProgressView *progressView;
    @end
    
    .m文件
    @interface ViewController ()
    {
        // 下载句柄
        NSURLSessionDownloadTask *_downloadTask;
    }
    

    2.利用AFN实现文件下载操作细节  

    - (void)downFileFromServer{
       
        //远程地址
        NSURL *URL = [NSURL URLWithString:@"http://www.baidu.com/img/bdlogo.png"];
        //默认配置
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
       
        //AFN3.0+基于封住URLSession的句柄
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
       
        //请求
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
       
        //下载Task操作
        _downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
           
            // @property int64_t totalUnitCount;     需要下载文件的总大小
            // @property int64_t completedUnitCount; 当前已经下载的大小
           
            // 给Progress添加监听 KVO
            NSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
            // 回到主队列刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
            // 设置进度条的百分比
    
                self.progressView.progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
            });
    
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
           
            //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径
    
            NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
            return [NSURL fileURLWithPath:path];
    
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            //设置下载完成操作
            // filePath就是你下载文件的位置,你可以解压,也可以直接拿来使用
           
            NSString *imgFilePath = [filePath path];// 将NSURL转成NSString
            UIImage *img = [UIImage imageWithContentsOfFile:imgFilePath];
            self.imageView.image = img;
    
        }];
    }
    

     3.关于暂停和继续  

    - (IBAction)stopDownloadBtnClick:(id)sender {
        //暂停下载
        [_downloadTask suspend];
    }
    - (IBAction)startDownloadBtnClick:(id)sender {
        //开始下载
        [_downloadTask resume];
    }
    

     4.检测网络状态--优化用户体验  

    - (void)viewDidLoad {
        [super viewDidLoad];
       
        //网络监控句柄
        AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
       
        //要监控网络连接状态,必须要先调用单例的startMonitoring方法
        [manager startMonitoring];
       
        [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            //status:
            //AFNetworkReachabilityStatusUnknown          = -1,  未知
            //AFNetworkReachabilityStatusNotReachable     = 0,   未连接
            //AFNetworkReachabilityStatusReachableViaWWAN = 1,   3G
            //AFNetworkReachabilityStatusReachableViaWiFi = 2,   无线连接
            NSLog(@"%d", status);
        }];
       
        //准备从远程下载文件. -> 请点击下面开始按钮启动下载任务
        [self downFileFromServer];
    
    }
    

    >> My GitHub:源码 https://github.com/SaupClear/AFNetworking3.0- 

    · AFNetworking3.0以下的版本使用方法可以看我老版本的日志:

    iOS- 利用AFNetworking(AFN) - 实现文件断点下载

    作者: 清澈Saup

    出处: http://www.cnblogs.com/qingche/

    本文版权归作者和博客园共有,欢迎转载,但必须保留此段声明,且在文章页面明显位置给出原文连接。

  • 相关阅读:
    ActiveMQ 即时通讯服务 浅析
    Asp.net Mvc (Filter及其执行顺序)
    ActiveMQ基本介绍
    ActiveMQ持久化消息的三种方式
    Windows Azure Virtual Machine (27) 使用psping工具,测试Azure VM网络连通性
    Azure China (10) 使用Azure China SAS Token
    Windows Azure Affinity Groups (3) 修改虚拟网络地缘组(Affinity Group)的配置
    Windows Azure Storage (22) Azure Storage如何支持多级目录
    Windows Azure Virtual Machine (26) 使用高级存储(SSD)和DS系列VM
    Azure Redis Cache (2) 创建和使用Azure Redis Cache
  • 原文地址:https://www.cnblogs.com/qingche/p/5362592.html
Copyright © 2011-2022 走看看