您的位置:首页 > 移动开发 > IOS开发

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

2014-01-01 17:12 567 查看

官方建议AFN的使用方法


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

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

@interface ViewController ()
{
// AFN的客户端,使用基本地址初始化,同时会实例化一个操作队列,以便于后续的多线程处理
AFHTTPClient    *_httpClient;

// 下载操作
AFHTTPRequestOperation *_downloadOperation;

NSOperationQueue *_queue;
}

//下载进度条显示
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@end

@implementation ViewController
/*
关于文件下载,在Documents中保存的文件,一定是要应用程序产生的文件或者数据
没有明显提示用户下载到本地的文件不能保存在Docuemnts中!

*/

- (void)viewDidLoad
{
[super viewDidLoad];

NSURL *url = [NSURL URLWithString:@"http://192.168.3.251/~apple/itcast"];
_httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

_queue = [[NSOperationQueue alloc] init];
}


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

#pragma mark 下载
- (IBAction)download
{
// 1. 建立请求
NSURLRequest *request = [_httpClient requestWithMethod:@"GET" path:@"download/Objective-C2.0.zip" parameters:nil];

// 2. 操作
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];

_downloadOperation = op;

// 下载
// 指定文件保存路径,将文件保存在沙盒中
NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [docs[0] stringByAppendingPathComponent:@"download.zip"];

op.outputStream = [NSOutputStream outputStreamToFileAtPath: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目录
*/
[SSZipArchive unzipFileAtPath:path toDestination:docs[0]];

// 解压缩之后,将原始的压缩包删除
// NSFileManager专门用于文件管理操作,可以删除,复制,移动文件等操作
// 也可以检查文件是否存在
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];

// 下一步可以进行进一步处理,或者发送通知给用户。
NSLog(@"下载成功");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"下载失败");
}];

// 启动下载
[_httpClient.operationQueue addOperation:op];
}


3.关于暂停和继续                 

- (IBAction)pauseResume:(id)sender
{
// 关于暂停和继续,AFN中的数据不是线程安全的
// 如果使用操作的暂停和继续,会使得数据发生混乱
// 不建议使用此功能。
// 有关暂停和后台下载的功能,NSURLSession中会介绍。
if (_downloadOperation.isPaused) {
[_downloadOperation resume];
} else {
[_downloadOperation pause];
}
}


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

#pragma mark 检测网路状态
/*
AFNetworkReachabilityStatusUnknown          = -1,  未知
AFNetworkReachabilityStatusNotReachable     = 0,   未连接
AFNetworkReachabilityStatusReachableViaWWAN = 1,   3G
AFNetworkReachabilityStatusReachableViaWiFi = 2,   无线连接
*/
- (IBAction)checkNetwork:(id)sender
{
// 1. AFNetwork 是根据是否能够连接到baseUrl来判断网络连接状态的
// 提示:最好使用门户网站来判断网络连接状态。
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];

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

[_httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

// 之所以区分无线和3G主要是为了替用户省钱,省流量
// 如果应用程序占流量很大,一定要提示用户,或者提供专门的设置,仅在无线网络时使用!
switch (status) {
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"无线网络");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"3G网络");
break;
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"未连接");
break;
case AFNetworkReachabilityStatusUnknown:
NSLog(@"未知错误");
break;
}
}];
}


                                                      

作者: 清澈Saup

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

                            

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: