使用NSURLConnection的同步方法下载



01. NSString *urlAsString = @"http://www.jouhu.com/json/info.zip";---要下载的全路径名
02. NSURL *url = [NSURL URLWithString:urlAsString];
03. NSURLRequest *request = [NSURLRequest requestWithURL:url];
04. NSError *error = nil;
05.  
06. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
07. /*下载的数据*/
08. if (data!=nil) {
09. NSLog(@"下载成功");
10. if ([data writeToFile:@"/Users/sunningning/Desktop/activation.zip"atomically:YES]) {--下载到目的路径名
11. NSLog(@"保存成功!");
12. }
13. else
14. {
15. NSLog(@"保存失败!");
16. }
17. }
18. else{
19. NSLog(@"%@",error);
20. }

2 使用NSURLConnection的异步方法下载


01. NSString *urlAsString = @"http://www.apple.com";
02. NSURL *url = [NSURL URLWithString:urlAsString];
03. NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
04. NSOperationQueue *queue = [[NSOperationQueue alloc] init];
05.  
06. [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error)
07. {
08. if ([data length] >0 && error == nil){
09. NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
10. NSLog(@"HTML = %@", html); }
11.  
12. else if ([data length] == 0 && error == nil){
13. NSLog(@"Nothing was downloaded.");
14. }
15.  
16. else if (error != nil){
17. NSLog(@"Error happened = %@", error); }
18. }];

3 使用NSURLConnection的异步+GCD的方法下载


01. + (void)performRequestWithUri:(NSString *)requestUri params:(NSDictionary *)params completionHandler:(void (^)(NSDictionary *, NSError *))completionBlock
02. {
03.  
04. // Generate the URL
05. NSString *requestUrl = [NSString stringWithFormat:@"http://the.api.com%@", requestUri];
06.  
07. // Create the connection
08. NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:requestUrl]];
09.  
10. // Make an NSOperationQueue
11. NSOperationQueue *queue = [[NSOperationQueue alloc] init];
12. [queue setName:@"com.your.unique.queue.name"];
13.  
14. // Send an asyncronous request on the queue
15. [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
16.  
17. // If there was an error getting the data
18. if (error) {
19.  
20. dispatch_async(dispatch_get_main_queue(), ^(void) {
21. completionBlock(nil, error);
22. });
23. return;
24. }
25.  
26. // Decode the data
27. NSError *jsonError;
28. NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
29.  
30. // If there was an error decoding the JSON
31. if (jsonError) {
32.  
33. dispatch_async(dispatch_get_main_queue(), ^(void) {
34.  
35. });
36. return;
37. }
38.  
39. // All looks fine, lets call the completion block with the response data
40. dispatch_async(dispatch_get_main_queue(), ^(void) {
41. completionBlock(responseDict, nil);
42. });
43. }];
44. }

具体调用方法:


1. [SHAPIController performRequestWithUri:@"http://www.jouhu.com/json/info.php"params:nil completionHandler:^(NSDictionary *response, NSError *error) {
2.  
3. if (error) {
4. NSLog(@"%@", error);
5. }
6.  
7. NSLog(@"%@", response);
8. }];

返回的数据根据我们而定.
4 实现delegate的方法实现异步


01. NSURLConnection *conn= [[NSURLConnection alloc]
02. initWithRequest:theRequest delegate:self];
03. [conn start];
04. if(conn)
05. {
06. NSLog(@"Connection Successful");
07. }
08. else
09. {
10. NSLog(@"Connection could not be made");
11. }
12. }

01. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)theResponse {
02. self.response = theResponse;
03. [data setLength:0]; // reset data
04. }
05.  
06. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData {
07. [data appendData:theData]; // append incoming data
08. }
09.  
10. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
11. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
12. self.data = nil;
13. if (handler) { [queue addOperationWithBlock:^{ handler(response, nil, error); }]; }
14. }
15.  
16. - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
17. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
18. // TODO: Are we passing the arguments to the block correctly? Should we copy them?
19. handleData(self.data);//处理数据,需要定义方法
20. }

我们自身的应用采用的是最后一种方法,对于很多图片更新的,可以采取第三种方法,第一种方法是同步数据下载,容易造成UI阻塞。需要注意。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值