i os 同步 异步 下载

同步下载文件:

复制代码
        NSString *urlAsString = @"http://files.cnblogs.com/zhuqil/UIWebViewDemo.zip";
NSURL
*url = [NSURL URLWithString:urlAsString];
NSURLRequest
*request = [NSURLRequest requestWithURL:url];
NSError
*error = nil;
NSData
*data = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:
&error];
/* 下载的数据 */
if (data != nil){
NSLog(
@"下载成功");
if ([data writeToFile:@"UIWebViewDemo.zip" atomically:YES]) {
NSLog(
@"保存成功.");
}
else
{
NSLog(
@"保存失败.");
}
}
else {
NSLog(
@"%@", error);
}
复制代码

异步下载文件:

复制代码
- (void)viewDidLoad
{
[super viewDidLoad];
//文件地址
NSString *urlAsString = @"http://files.cnblogs.com/zhuqil/UIWebViewDemo.zip";
NSURL
*url = [NSURL URLWithString:urlAsString];
NSURLRequest
*request = [NSURLRequest requestWithURL:url];
NSMutableData
*data = [[NSMutableData alloc] init];
self.connectionData
= data;
[data release];
NSURLConnection
*newConnection = [[NSURLConnection alloc]
initWithRequest:request
delegate:self
startImmediately:YES];
self.connection
= newConnection;
[newConnection release];
if (self.connection != nil){
NSLog(
@"Successfully created the connection");
}
else {
NSLog(
@"Could not create the connection");
}
}




- (void) connection:(NSURLConnection *)connection
didFailWithError:(NSError
*)error{
NSLog(
@"An error happened");
NSLog(
@"%@", error);
}
- (void) connection:(NSURLConnection *)connection
didReceiveData:(NSData
*)data{
NSLog(
@"Received data");
[self.connectionData appendData:data];
}
- (void) connectionDidFinishLoading
:(NSURLConnection
*)connection{
/* 下载的数据 */

NSLog(
@"下载成功");
if ([self.connectionData writeToFile:@"UIWebViewDemo.zip" atomically:YES]) {
NSLog(
@"保存成功.");
}
else
{
NSLog(
@"保存失败.");
}

/* do something with the data here */
}
- (void) connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse
*)response{
[self.connectionData setLength:
0];
}

- (void) viewDidUnload{
[super viewDidUnload];
[self.connection cancel];
self.connection
= nil;
self.connectionData
= nil;
}

你可能感兴趣的:(i os 同步 异步 下载)