经常使用iOS第三方网路框架

–AFNetworking(AFN)
新建项目并导入 AFN 框架 的步骤
•1. 将框架程序拖拽进项目
•2.  添加iOS框架引用
–SystemConfiguration.framework
–MobileCoreServices.framework
•3. 修改xxx-Prefix.pch文件

#import <MobileCoreServices/MobileCoreServices.h>php

#import <SystemConfiguration/SystemConfiguration.h>html

AFN——AFHTTPClientjson

•1. 使用baseURL实例化
•2. 创建NSURLRequest
Ø建立GET、HEAD、PUT、DELETE方法请求
²requestWithMethod:path:parameters:
Ø建立POST方法请求
²multipartFormRequestWithMethod:path:parameters:
constructingBodyWithBlock:

 

•3. 检测网路链接状态
–setReachabilityStatusChangeBlock
 
AFHttpRequestOperation —— NSURLConnection 的封装
•AFHttpRequestOperation  HTTP请求操做
ØAFJSONRequestOperation  对JSON请求的封装
ØAFXMLRequestOperation  对XML请求的封装
ØAFPropertyListRequestOperation  对Plist请求的封装
ØAFImageRequestOperation  对图像请求的封装
Ø
•块代码操做
ØsetCompletionBlockWithSuccess  设置请求完成块代码
ØsetUploadProgressBlock  设置上传进度块代码
ØsetDownloadProgressBlock  设置下载进度块代码
•下载操做须要设置outputStream
Ø针对请求的操做pause(暂停)resume(继续)

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

    // 若是使用操做的暂停和继续,会使得数据发生混乱服务器

    // 不建议使用此功能。网络

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

    if (_downloadOperation.isPaused) {app

        [_downloadOperationresume];框架

    } else {ide

        [_downloadOperationpause];

    }

 

检测网络链接状态
 AFNetworkReachabilityStatusUnknown           = -1,   未知

 AFNetworkReachabilityStatusNotReachable     = 0,   未链接

 AFNetworkReachabilityStatusReachableViaWWAN = 1,   3G

 AFNetworkReachabilityStatusReachableViaWiFi = 2,   无线链接

// 1. AFNetwork 是根据是否可以链接到baseUrl来判断网络链接状态的

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

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

    

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

    _httpClient = client;

    

    [_httpClientsetReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

 

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

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

        switch (status) {

            caseAFNetworkReachabilityStatusReachableViaWiFi:

                NSLog(@"无线网络");

                break;

            caseAFNetworkReachabilityStatusReachableViaWWAN:

                NSLog(@"3G网络");

                break;

            caseAFNetworkReachabilityStatusNotReachable:

                NSLog(@"未链接");

                break;

            caseAFNetworkReachabilityStatusUnknown:

                NSLog(@"未知错误");

                break;

        }

 

    }];

 

 

加载JSON 

官方建议AFN的使用方法

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

    1> baseURL

    2> 请求

    3> 操做队列 NSOperationQueue

 2. AFHTTPRequestOperation负责全部的网络操做请求

// 1. NSURLRequest

    NSURLRequest *request = [_httpClientrequestWithMethod:@"GET"path:@"videos.php?format=json"parameters:nil];

    

    // 2. 链接

    AFJSONRequestOperation *op = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSArray *JSON) {

        

        // 成功以后,直接使用反序列化出来的结果便可。

        NSLog(@"%@", JSON);

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {

        // 1> 网络访问获取数据出错

        // 2> JSON的反序列化出错

        

        NSLog(@"%@ %@", error, JSON);

    }];

    

    // 3. 将操做添加到队列,开始多线程操做

    // 将操做添加到队列或者start,操做就会启动

    [_httpClient.operationQueueaddOperation:op];

//    [_queue addOperation:op];

 

//    [op start];

 

上传图像

  /*

     此段代码若是须要修改,能够调整的位置

     

     1. upload.php改为网站开发人员告知的地址

     2. file改为网站开发人员告知的字段名

     */

    // 1. httpClient->url

    

    // 2. 上传请求POST

    NSURLRequest *request = [_httpClientmultipartFormRequestWithMethod:@"POST"path:@"upload.php"parameters:nilconstructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        // 在此位置生成一个要上传的数据体

        // form对应的是html文件中的表单

        /*

         参数

         1. 要上传的[二进制数据]

         2. 对应网站上[upload.php]处理文件的[字段"file"]

         3. 要保存在服务器上的[文件名]

         4. 上传文件的[mimeType]

         */

        UIImage *image = [UIImage imageNamed:@"头像1"];

        NSData *data = UIImagePNGRepresentation(image);

        

        // 在网络开发中,上传文件时,是文件不容许被覆盖,文件重名

        // 要解决此问题,

        // 能够在上传时使用当前的系统事件做为文件名

        NSDateFormatter *formatter = [[NSDateFormatteralloc] init];

        // 设置时间格式

        formatter.dateFormat = @"yyyyMMddHHmmss";

        NSString *str = [formatter stringFromDate:[NSDate date]];

        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];

        

        [formData appendPartWithFileData:data name:@"file"fileName:fileName mimeType:@"image/png"];

    }];

    

    // 3. operation包装的urlconnetion

    AFHTTPRequestOperation *op = [[AFHTTPRequestOperationalloc] initWithRequest:request];

    

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

        NSLog(@"上传完成");

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

        NSLog(@"上传失败->%@", error);

    }];

    

    

    [_httpClient.operationQueueaddOperation:op];

 

——断点续传

•设置操做的输出流(在网络中的数据是流的方式传输)
•[operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:downloadPath append:YES]];
 

下载

    // 1. 创建请求

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

    

    // 2. 操做

    AFHTTPRequestOperation *op = [[AFHTTPRequestOperationalloc] initWithRequest:request];

    

    _downloadOperation = op;

    

    // 下载

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

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

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

    

    op.outputStream = [NSOutputStreamoutputStreamToFileAtPath:path append:NO];

    

    // 设置下载进程块代码

    /*

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

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

     totalBytesExpectedToRead       文件总大小(5M)

     */

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

        

        // 设置进度条的百分比

        CGFloat precent = (CGFloat)totalBytesRead / totalBytesExpectedToRead;

        NSLog(@"%f", precent);

        

        _progressView.progress = precent;

    }];

    

    // 设置下载完成操做

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

        

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

        /*

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

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

         */

        [SSZipArchiveunzipFileAtPath:path toDestination:docs[0]];

        

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

        // NSFileManager专门用于文件管理操做,能够删除,复制,移动文件等操做

        // 也能够检查文件是否存在

        [[NSFileManagerdefaultManager] removeItemAtPath:path error:nil];

        

        // 下一步能够进行进一步处理,或者发送通知给用户。

        NSLog(@"下载成功");

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

        NSLog(@"下载失败");

    }];

    

    // 启动下载

    [_httpClient.operationQueueaddOperation:op];

相关文章
相关标签/搜索