NSURLRequest 同步和异步

同步下载:

-(void)downloadSynJarFiles

{

    NSString *urlAsString = @"http://192.168.1.196:8080/PlaceNaviServer/WEB-INF/lib/activation.jar";---要下载的全路径名

    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:@"/Users/sunningning/Desktop/activation.jar" atomically:YES]) {--下载到目的路径名

            NSLog(@"保存成功!");

        }

        else

        {

            NSLog(@"保存失败!");

        }

    }

    else{

        NSLog(@"%@",error);

    }

}



异步下载:

//异步

-(void)downloadAsnJarFiles

{

    NSString *urlAsString = @"http://192.168.1.196:8080/PlaceNaviServer/WEB-INF/lib/activation.jar";

    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 (connection !=nil) {

        NSLog(@"Successfully create the connection");

    }

    else{

        NSLog(@"can 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(@"receive data");


    [self.connectionData  appendData:data];--这里才真正意义的取值和赋值

}


-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSLog(@"haha----");

    /*下载数据*/

    if ([self.connectionData writeToFile:@"/Users/sunningning/Desktop/activation.jar" atomically:YES]) {--保存到目的路径

        NSLog(@"保存成功!");

    }

    else

    {

        NSLog(@"保存失败!");

    }

    

    /*处理data*/

}


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

{

    [self.connectionData setLength:0];

}


- (void)viewDidUnload

{

    [super viewDidUnload];

    // Release any retained subviews of the main view.

    // e.g. self.myOutlet = nil;

    [self.connection cancel];//取消连接

    self.connectionData = nil;//属性

    self.connection = nil;//属性

}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值