nsurlsession 的基本用法

1、下载天气预报数据,使用的是 forecast.io 的天气预报接口,需要自行设置 apiKey

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  RWWeatherViewController.m  
  3. //  TroutTrip  
  4. //  
  5. //  Created by Charlie Fulton on 2/26/14.  
  6. //  Copyright (c) 2014 Ray Wenderlich Tutorials. All rights reserved.  
  7. //  
  8.   
  9. #import "RWWeatherDataTaskViewController.h"  
  10.   
  11. #warning THIS IS WHERE YOU SET YOUR FORECAST.IO KEY  
  12. // see https://developer.forecast.io/docs/v2 for details  
  13. static NSString constconst *kApiKey = @"YOUR_API_KEY";  
  14.   
  15. @interface RWWeatherDataTaskViewController ()  
  16.   
  17. @property (nonatomicstrongNSDictionary *weatherData;  
  18.   
  19.   
  20. @property (weak, nonatomic) IBOutlet UILabel *currentConditionsLabel;  
  21. @property (weak, nonatomic) IBOutlet UILabel *tempLabel;  
  22.   
  23. @property (weak, nonatomic) IBOutlet UITextView *summary;  
  24.   
  25. @end  
  26.   
  27.   
  28.   
  29. @implementation RWWeatherDataTaskViewController  
  30.   
  31. #pragma mark - Lifecycle  
  32.   
  33. - (void)viewDidLoad {  
  34.   [super viewDidLoad];  
  35.     
  36.     //1  
  37.     NSString *dataUrl = [NSString stringWithFormat:@"https://api.forecast.io/forecast/%@/38.936320,-79.223550",kApiKey];  
  38.     NSURL *url = [NSURL URLWithString:dataUrl];  
  39.       
  40.     // 2  
  41.     NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession]  
  42.     dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {  
  43.         
  44.       // Check to make sure the server didn't respond with a "Not Authorized"  
  45.       if ([response respondsToSelector:@selector(statusCode)]) {  
  46.         if ([(NSHTTPURLResponse *) response statusCode] == 403) {  
  47.           dispatch_async(dispatch_get_main_queue(), ^{  
  48.             // Remind the user to update the API Key  
  49.             UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"API Key Needed"  
  50.                                                              message:@"Check the forecast.io API key in RWWeatherDataTaskViewController.m"  
  51.                                                             delegate:nil  
  52.                                                    cancelButtonTitle:@"OK"  
  53.                                                    otherButtonTitles:nil];  
  54.             [alert show];  
  55.             return;  
  56.           });  
  57.         }  
  58.       }  
  59.         
  60.       // 4: Handle response here  
  61.       [self processResponseUsingData:data];  
  62.         
  63.   }];  
  64.       
  65.     // 3  
  66.     [downloadTask setTaskDescription:@"weatherDownload"];  
  67.     [downloadTask resume];  
  68. }  
  69.   
  70.   
  71.   
  72. #pragma mark - Private  
  73.   
  74. // Helper method, maybe just make it a category..  
  75. - (void)processResponseUsingData:(NSData*)data {  
  76.   NSError *parseJsonError = nil;  
  77.     
  78.   NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data  
  79.                                                            options:NSJSONReadingAllowFragments error:&parseJsonError];  
  80.   if (!parseJsonError) {  
  81.     NSLog(@"json data = %@", jsonDict);  
  82.         dispatch_async(dispatch_get_main_queue(), ^{  
  83.             self.currentConditionsLabel.text = jsonDict[@"currently"][@"summary"];  
  84.             self.tempLabel.text = [jsonDict[@"currently"][@"temperature"]stringValue];  
  85.             self.summary.text = jsonDict[@"daily"][@"summary"];  
  86.         });  
  87.   }  
  88. }  
  89.   
  90.   
  91. @end  

2、使用NSURLSession下载图片

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  RWLocationViewController.m  
  3. //  TroutTrip  
  4. //  
  5. //  Created by Charlie Fulton on 2/28/14.  
  6. //  Copyright (c) 2014 Ray Wenderlich Tutorials. All rights reserved.  
  7. //  
  8.   
  9. #import "RWLocationDownloadTaskViewController.h"  
  10.   
  11. @interface RWLocationDownloadTaskViewController ()  
  12.   
  13. @property (weak, nonatomic) IBOutlet UIImageView *locationPhoto;  
  14. @property (weak, nonatomic) IBOutlet UIView *pleaseWait;  
  15.   
  16. @end  
  17.   
  18. @implementation RWLocationDownloadTaskViewController  
  19.   
  20.   
  21. - (void)viewDidLoad {  
  22.   [super viewDidLoad];  
  23.       
  24.     self.pleaseWait.hidden = NO;  
  25.       
  26.     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];  
  27.       
  28.   // 1  
  29.     NSURL *url = [NSURL URLWithString:  
  30.     @"http://upload.wikimedia.org/wikipedia/commons/7/7f/Williams_River-27527.jpg"];  
  31.       
  32.   // 2  
  33.     NSURLSessionDownloadTask *downloadPhotoTask =[[NSURLSession sharedSession]  
  34.     downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {  
  35.         
  36.       [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];  
  37.       self.pleaseWait.hidden = YES;  
  38.         
  39.       // 3  
  40.       UIImage *downloadedImage = [UIImage imageWithData:  
  41.         [NSData dataWithContentsOfURL:location]];  
  42.         
  43.       // Handle the downloaded image  
  44.   
  45.       // Save the image to your Photo Album  
  46.       UIImageWriteToSavedPhotosAlbum(downloadedImage, nil, nil, nil);  
  47.         
  48.       dispatch_async(dispatch_get_main_queue(), ^{  
  49.         NSLog(@"updating UIImageView");  
  50.         self.locationPhoto.image = downloadedImage;  
  51.       });  
  52.     }];  
  53.       
  54.   // 4  
  55.     [downloadPhotoTask resume];  
  56. }  
  57.   
  58.   
  59. @end  

3、使用NSURLSession上传数据(同样需要自行设置 appid 和 apikey,具体参考代码中给出的链接)

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  RWStoryViewController.m  
  3. //  TroutTrip  
  4. //  
  5. //  Created by Charlie Fulton on 2/26/14.  
  6. //  Copyright (c) 2014 Ray Wenderlich Tutorials. All rights reserved.  
  7. //  
  8.   
  9. #import "RWStoryUploadTaskViewController.h"  
  10.   
  11. #warning THIS IS WHERE YOU SET YOUR PARSE.COM API KEYS  
  12. // see : http://www.raywenderlich.com/19341/how-to-easily-create-a-web-backend-for-your-apps-with-parse  
  13. // https://parse.com/tutorials  
  14. static NSString constconst *kAppId = @"YOUR_APP_KEY";  
  15. static NSString constconst *kRestApiKey = @"YOUR_REST_API_KEY";  
  16.   
  17. @interface RWStoryUploadTaskViewController ()  
  18. @property (weak, nonatomic) IBOutlet UITextField *story;  
  19.   
  20. @end  
  21.   
  22. @implementation RWStoryUploadTaskViewController  
  23.   
  24.   
  25. #pragma mark Private  
  26.   
  27. - (IBAction)postStory:(id)sender {  
  28.       
  29.     // 1  
  30.     NSURL *url = [NSURL URLWithString:@"https://api.parse.com/1/classes/FishStory"];  
  31.     NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];  
  32.   
  33.     // Parse requires HTTP headers for authentication. Set them before creating your NSURLSession  
  34.   [config setHTTPAdditionalHeaders:@{@"X-Parse-Application-Id":kAppId,  
  35.                                      @"X-Parse-REST-API-Key":kRestApiKey,  
  36.                                      @"Content-Type"@"application/json"}];  
  37.       
  38.     NSURLSession *session = [NSURLSession sessionWithConfiguration:config];  
  39.   
  40.     
  41.     // 2  
  42.     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];  
  43.     request.HTTPMethod = @"POST";  
  44.   
  45.     
  46.   // 3  
  47.     NSDictionary *dictionary = @{@"story"self.story.text};  
  48.     NSError *error = nil;  
  49.     NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary  
  50.       options:kNilOptions error:&error];  
  51.       
  52.     if (!error) {  
  53.         // 4  
  54.         NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request  
  55.       fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {  
  56.               
  57.         // Check to make sure the server didn't respond with a "Not Authorized"  
  58.         if ([response respondsToSelector:@selector(statusCode)]) {  
  59.           if ([(NSHTTPURLResponse *) response statusCode] == 401) {  
  60.             dispatch_async(dispatch_get_main_queue(), ^{  
  61.               // Remind the user to update the API Key  
  62.               UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"API Key Needed"  
  63.                                                                message:@"Check the Parse App and Rest API keys in RWStoryUploadTaskViewController.m"  
  64.                                                               delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];  
  65.               [alert show];  
  66.               return;  
  67.             });  
  68.           }  
  69.         }  
  70.           
  71.         if (!error) {  
  72.           // Data was created, we leave it to you to display all of those tall tales!  
  73.           dispatch_async(dispatch_get_main_queue(), ^{  
  74.             self.story.text = @"";  
  75.           });  
  76.             
  77.         } else {  
  78.           NSLog(@"DOH");  
  79.         }  
  80.         }];  
  81.           
  82.     // 5  
  83.         [uploadTask resume];  
  84.     }  
  85. }  
  86.   
  87.   
  88. @end  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
NSURLSessionCorrectedResumeData是一个iOS开发中的类,用于处理网络请求的断点续传功能。 在网络请求过程中,由于各种原因(如网络不稳定或用户手动停止请求),请求可能会中断。为了方便用户继续中断的请求,苹果提供了NSURLSessionCorrectedResumeData来恢复中断的请求。 NSURLSessionCorrectedResumeData是一个二进制数据,它包含了中断请求的具体信息,如请求的URL、请求的方法、请求头信息、请求体等。开发者可以将这个数据保存到本地,以便在下次启动应用时重新发起请求。 当应用再次启动并需要继续中断的请求时,开发者可以使用NSURLSession的resumeData属性来读取之前保存的NSURLSessionCorrectedResumeData数据。 然后,开发者可以通过NSURLSession的downloadTask(withCorrectedResumeData:completionHandler:)方法来恢复请求。这个方法会根据传入的NSURLSessionCorrectedResumeData创建一个下载任务,并在下载完成后调用回调函数。 需要注意的是,正确使用NSURLSessionCorrectedResumeData需要遵循一些特定的规则。比如,只有之前使用NSURLSession的downloadTask方法发起的请求才能使用相关的恢复方法,并且不能保证100%的恢复成功。 总结来说,NSURLSessionCorrectedResumeData提供了一种方便的方式来处理网络请求中的断点续传功能,并且提高了用户体验。通过保存和恢复NSURLSessionCorrectedResumeData数据,开发者可以更加灵活地处理中断的请求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值