zoukankan      html  css  js  c++  java
  • iOS- 利用AFNetworking(AFN)

    https://www.cnblogs.com/qingche/p/3500746.html

    1. 定义一个全局的AFHttpClient:包含有

        1> baseURL

        2> 请求

        3> 操作队列 NSOperationQueue

     2. 由AFHTTPRequestOperation负责所有的网络操作请求

    0.导入框架准备工作                                

    •1. 将框架程序拖拽进项目

    •2.  添加iOS框架引用

    –SystemConfiguration.framework

    –MobileCoreServices.framework

    •3.  引入

    #import "AFNetworking.h"

    //下面用于下载完后解压

    #import "SSZipArchive.h"

     4. 修改xxx-Prefix.pch文件

    #import <MobileCoreServices/MobileCoreServices.h>

    #import <SystemConfiguration/SystemConfiguration.h>

    1.AFN的客户端,使用基本地址初始化,同时会实例化一个操作队列,以便于后续的多线程处理

    pastedGraphic.png

     1 #import "ViewController.h"

     2 #import "AFNetworking.h"

     3 #import "SSZipArchive.h"

     4 

     5 @interface ViewController ()

     6 {

     7     // AFN的客户端,使用基本地址初始化,同时会实例化一个操作队列,以便于后续的多线程处理

     8     AFHTTPClient    *_httpClient;

     9     

    10     // 下载操作

    11     AFHTTPRequestOperation *_downloadOperation;

    12     

    13     NSOperationQueue *_queue;

    14 }

    15 

    //下载进度条显示

    16 @property (weak, nonatomic) IBOutlet UIProgressView *progressView;

    17 

    18 @end

    19 

    20 @implementation ViewController

    21 /*

    22  关于文件下载,在Documents中保存的文件,一定是要应用程序产生的文件或者数据

    23  没有明显提示用户下载到本地的文件不能保存在Docuemnts中!

    24  

    25  

    26  */

    27 

    28 - (void)viewDidLoad

    29 {

    30     [super viewDidLoad];

    31     

    32     NSURL *url = [NSURL URLWithString:@"http://192.168.3.251/~apple/itcast"];

    33     _httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

    34     

    35     _queue = [[NSOperationQueue alloc] init];

    36 }

    pastedGraphic.png

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

    pastedGraphic.png

     1 #pragma mark 下载

     2 - (IBAction)download

     3 {

     4     // 1. 建立请求

     5     NSURLRequest *request = [_httpClient requestWithMethod:@"GET" path:@"download/Objective-C2.0.zip" parameters:nil];

     6     

     7     // 2. 操作

     8     AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];

     9     

    10     _downloadOperation = op;

    11     

    12     // 下载

    13     // 指定文件保存路径,将文件保存在沙盒中

    14     NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    15     NSString *path = [docs[0] stringByAppendingPathComponent:@"download.zip"];

    16     

    17     op.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

    18     

    19     // 设置下载进程块代码

    20     /*

    21      bytesRead                      当前一次读取的字节数(100k)

    22      totalBytesRead                 已经下载的字节数(4.9M)

    23      totalBytesExpectedToRead       文件总大小(5M)

    24      */

    25     [op setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

    26         

    27         // 设置进度条的百分比

    28         CGFloat precent = (CGFloat)totalBytesRead / totalBytesExpectedToRead;

    29         NSLog(@"%f", precent);

    30         

    31         _progressView.progress = precent;

    32     }];

    33     

    34     // 设置下载完成操作

    35     [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    36         

    37         // 下载完成之后,解压缩文件

    38         /*

    39          参数1:要解结压缩的文件名及路径 path - > download.zip

    40          参数2:要解压缩到的位置,目录    - > document目录

    41          */

    42         [SSZipArchive unzipFileAtPath:path toDestination:docs[0]];

    43         

    44         // 解压缩之后,将原始的压缩包删除

    45         // NSFileManager专门用于文件管理操作,可以删除,复制,移动文件等操作

    46         // 也可以检查文件是否存在

    47         [[NSFileManager defaultManager] removeItemAtPath:path error:nil];

    48         

    49         // 下一步可以进行进一步处理,或者发送通知给用户。

    50         NSLog(@"下载成功");

    51     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    52         NSLog(@"下载失败");

    53     }];

    54     

    55     // 启动下载

    56     [_httpClient.operationQueue addOperation:op];

    57  }

    pastedGraphic.png

    3.关于暂停和继续                 

    pastedGraphic.png

     1 - (IBAction)pauseResume:(id)sender

     2 {

     3     // 关于暂停和继续,AFN中的数据不是线程安全的

     4     // 如果使用操作的暂停和继续,会使得数据发生混乱

     5     // 不建议使用此功能。

     6     // 有关暂停和后台下载的功能,NSURLSession中会介绍。

     7     if (_downloadOperation.isPaused) {

     8         [_downloadOperation resume];

     9     } else {

    10         [_downloadOperation pause];

    11     }

    12 }

    pastedGraphic.png

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

    pastedGraphic.png

     1 #pragma mark 检测网路状态

     2 /*

     3  AFNetworkReachabilityStatusUnknown          = -1,  未知

     4  AFNetworkReachabilityStatusNotReachable     = 0,   未连接

     5  AFNetworkReachabilityStatusReachableViaWWAN = 1,   3G

     6  AFNetworkReachabilityStatusReachableViaWiFi = 2,   无线连接

     7  */

     8 - (IBAction)checkNetwork:(id)sender

     9 {

    10     // 1. AFNetwork 是根据是否能够连接到baseUrl来判断网络连接状态的

    11     // 提示:最好使用门户网站来判断网络连接状态。

    12     NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];

    13     

    14     AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:url];

    15     _httpClient = client;

    16     

    17     [_httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

    18 

    19         // 之所以区分无线和3G主要是为了替用户省钱,省流量

    20         // 如果应用程序占流量很大,一定要提示用户,或者提供专门的设置,仅在无线网络时使用!

    21         switch (status) {

    22             case AFNetworkReachabilityStatusReachableViaWiFi:

    23                 NSLog(@"无线网络");

    24                 break;

    25             case AFNetworkReachabilityStatusReachableViaWWAN:

    26                 NSLog(@"3G网络");

    27                 break;

    28             case AFNetworkReachabilityStatusNotReachable:

    29                 NSLog(@"未连接");

    30                 break;

    31             case AFNetworkReachabilityStatusUnknown:

    32                 NSLog(@"未知错误");

    33                 break;

    34         }

    35     }];

    36 }

    pastedGraphic.png

    · AFNetworking3.0+ (最新AFN) 版本使用方法可以看我最新的日志:

    iOS- 利用AFNetworking3.0+(最新AFN) - 实现文件断点下载

    0.导入框架准备工作  

    ·1. 将AFNetworking3.0+框架程序拖拽进项目

     

    ·2. 或使用Cocopod 导入AFNetworking3.0+

     

    ·3.  引入

    #import "AFNetworking.h"

    pastedGraphic.png---->pastedGraphic_1.png

    1.UI准备工作  

    A. 定义一个全局的 NSURLSessionDownloadTask:下载管理句柄

       由其负责所有的网络操作请求

    1

    2

    3

    4

    5

    @interface ViewController ()

    {

        // 下载句柄

        NSURLSessionDownloadTask *_downloadTask;

    }

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    .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实现文件下载操作细节  

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    - (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.关于暂停和继续  

    1

    2

    3

    4

    5

    6

    7

    8

    - (IBAction)stopDownloadBtnClick:(id)sender {

        //暂停下载

        [_downloadTask suspend];

    }

    - (IBAction)startDownloadBtnClick:(id)sender {

        //开始下载

        [_downloadTask resume];

    }

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    - (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- 

  • 相关阅读:
    flutter开发环境的搭建
    创建一个android项目
    android studio 安装与配置
    sentinel-dashboard.jar 安装
    三:nacos的配置中心
    二:nacos 的服务注册
    spring boot 在windows下的 批文件部署
    一:nacos 的安装与启动方式
    mysql 命令行安装方式
    Git 出现 Permission denied 时,重新生成ssh密钥
  • 原文地址:https://www.cnblogs.com/sundaysgarden/p/10521569.html
Copyright © 2011-2022 走看看