IOS的同步下载及异步下载

来源:互联网 发布:中国电力人才网络联盟 编辑:程序博客网 时间:2024/04/29 10:23

下载就是把云端的信息,传输到本地。换句话说,只要是获得本地没有的信息操作,都可以成为下载。

先介绍IOS自带的两种下载方式:同步下载和异步下载。

同步下载的时候,该线程进入挂起、假死状态,等到全部下载完成,才能进行其他操作。在这期间,用户对界面的操作都是无效的,界面也不会响应任何事件。

另外一种是异步下载,异步下载的时候,用户还可以对界面进行操作,界面也可以响应事件。

从用户友好度的角度来说,异步下载的用户友好度远高于同步下载。我们平时操作的下载基本也都是异步下载。

IOS的异步下载需要实现NSURLConnectionDelegate里的4个代理方法(开始下载,下载中,完成下载,出错)

下面是代码:

创建一个带xib的ViewController,在上面创建2个按钮,分别是同步下载和异步下载

ViewController.h文件:

#import <UIKit/UIKit.h>

@interface ViewController :UIViewController<NSURLConnectionDelegate>

@property (assign,nonatomic)long long allLength;

@property (assign,nonatomic)long long lastAllLength;

@property (assign,nonatomic)long long downLoadingSpeed;

@property (retain,nonatomic)NSMutableData * allData;

//用于显示进度条

@property (retain,nonatomic)UIProgressView * progressView;

//用于显示进度

@property (retain,nonatomic)UILabel * labelProgress;

//用于显示下载速度

@property (retain,nonatomic)UILabel * labelDownLoadingSpeed;

@end


ViewController.m实现文件部分:

#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController

#pragma mark - 同步下载按钮方法

- (IBAction)DownLoad:(id)sender {

    //创建一个NSURL对象

    NSURL * url = [NSURLURLWithString:@"http://bg.265g.com/1305/115432.html"];

    //创建一个NSrequest对象

    NSURLRequest * request = [NSURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:7];

    //发送request

   NSError * err = [NSErroralloc];

    NSData * data = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:&err];

    //保存接受到的数据

    [data writeToFile:@"/Users/ibokan/Desktop/bbb.html"atomically:YES];

}

#pragma mark - 异步下载按钮方法

- (IBAction)yibu:(id)sender {

    //创建NSURL对象

    NSURL * url = [NSURLURLWithString:@"http://yinyueshiting.baidu.com/data2/music/49919223/978262252000320.mp3?xcode=2d7d268ae3c96e23d98123b24900397e263f5c6ee17ec294"];

    //创建REQUEST对象

    NSURLRequest * request = [NSURLRequestrequestWithURL:url cachePolicy:0timeoutInterval:10];

    //创建NSURLCONNECTION对象,并设置代理

    [NSURLConnectionconnectionWithRequest:request delegate:self];

}

#pragma mark - NSURLConnectionDelegate

-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

   self.allData = [[NSMutableDataalloc]init];

    self.allLength = response.expectedContentLength;

    NSLog(@"服务器已响应,开始接受数据");

}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [self.allDataappendData:data];

   long long x =self.allData.length *100/self.allLength;

    NSLog(@"正在接受数据,%lld%@",x,@"%");

    //计算进度条位置

    _progressView.progress =self.allData.length *1.0 / self.allLength;

   /*

    //计算下载速度

    _downLoadingSpeed = _allData.length - _lastAllLength;

    _labelDownLoadingSpeed.text = [NSString stringWithFormat:@"%lldKB/s",_downLoadingSpeed/1000];

    _lastAllLength = _allData.length;

     */

    //计算进度

    _labelProgress.text = [NSStringstringWithFormat:@"%dKB/%lldKB",self.allData.length/1000,self.allLength/1000];

}

-(void) connectionDidFinishLoading:(NSURLConnection *)connection {

    [self.allDatawriteToFile:@"/users/ibokan/desktop/a.mp3"atomically:YES];

    NSLog(@"数据接受完成");

}

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

    NSLog(@"数据连接失败,错误为:%@",error);

}

#pragma end mark

- (void)viewDidLoad {

    [superviewDidLoad];

    _progressView = [[UIProgressViewalloc]initWithFrame:CGRectMake(20,20, 200, 20)];

    _progressView.progress =0;

    [self.viewaddSubview:_progressView];

    _labelProgress = [[UILabelalloc]initWithFrame:CGRectMake(20,50, 200, 20)];

    _labelProgress.text =@"0 KB/0 KB";

    [self.viewaddSubview:_labelProgress];

   /*

    _labelDownLoadingSpeed = [[UILabel alloc]initWithFrame:CGRectMake(230, 20, 70, 20)];

    _labelDownLoadingSpeed.text = @" 0 KB/s";

    [self.view addSubview:_labelDownLoadingSpeed];

     */

}

- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end