首页 > 代码库 > 使用NSURLSession进行上传下载
使用NSURLSession进行上传下载
1、下载天气预报数据。使用的是 forecast.io 的天气预报接口,须要自行设置 apiKey
// // RWWeatherViewController.m // TroutTrip // // Created by Charlie Fulton on 2/26/14. // Copyright (c) 2014 Ray Wenderlich Tutorials. All rights reserved. // #import "RWWeatherDataTaskViewController.h" #warning THIS IS WHERE YOU SET YOUR FORECAST.IO KEY // see https://developer.forecast.io/docs/v2 for details static NSString const *kApiKey = @"YOUR_API_KEY"; @interface RWWeatherDataTaskViewController () @property (nonatomic, strong) NSDictionary *weatherData; @property (weak, nonatomic) IBOutlet UILabel *currentConditionsLabel; @property (weak, nonatomic) IBOutlet UILabel *tempLabel; @property (weak, nonatomic) IBOutlet UITextView *summary; @end @implementation RWWeatherDataTaskViewController #pragma mark - Lifecycle - (void)viewDidLoad { [super viewDidLoad]; //1 NSString *dataUrl = [NSString stringWithFormat:@"https://api.forecast.io/forecast/%@/38.936320,-79.223550",kApiKey]; NSURL *url = [NSURL URLWithString:dataUrl]; // 2 NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // Check to make sure the server didn't respond with a "Not Authorized" if ([response respondsToSelector:@selector(statusCode)]) { if ([(NSHTTPURLResponse *) response statusCode] == 403) { dispatch_async(dispatch_get_main_queue(), ^{ // Remind the user to update the API Key UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"API Key Needed" message:@"Check the forecast.io API key in RWWeatherDataTaskViewController.m" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; return; }); } } // 4: Handle response here [self processResponseUsingData:data]; }]; // 3 [downloadTask setTaskDescription:@"weatherDownload"]; [downloadTask resume]; } #pragma mark - Private // Helper method, maybe just make it a category.. - (void)processResponseUsingData:(NSData*)data { NSError *parseJsonError = nil; NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&parseJsonError]; if (!parseJsonError) { NSLog(@"json data = http://www.mamicode.com/%@", jsonDict);>
2、使用NSURLSession下载图片// // RWLocationViewController.m // TroutTrip // // Created by Charlie Fulton on 2/28/14. // Copyright (c) 2014 Ray Wenderlich Tutorials. All rights reserved. // #import "RWLocationDownloadTaskViewController.h" @interface RWLocationDownloadTaskViewController () @property (weak, nonatomic) IBOutlet UIImageView *locationPhoto; @property (weak, nonatomic) IBOutlet UIView *pleaseWait; @end @implementation RWLocationDownloadTaskViewController - (void)viewDidLoad { [super viewDidLoad]; self.pleaseWait.hidden = NO; [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; // 1 NSURL *url = [NSURL URLWithString: @"http://upload.wikimedia.org/wikipedia/commons/7/7f/Williams_River-27527.jpg"]; // 2 NSURLSessionDownloadTask *downloadPhotoTask =[[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) { [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; self.pleaseWait.hidden = YES; // 3 UIImage *downloadedImage = [UIImage imageWithData: [NSData dataWithContentsOfURL:location]]; // Handle the downloaded image // Save the image to your Photo Album UIImageWriteToSavedPhotosAlbum(downloadedImage, nil, nil, nil); dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"updating UIImageView"); self.locationPhoto.image = downloadedImage; }); }]; // 4 [downloadPhotoTask resume]; } @end
3、使用NSURLSession上传数据(相同须要自行设置 appid 和 apikey。详细參考代码中给出的链接)// // RWStoryViewController.m // TroutTrip // // Created by Charlie Fulton on 2/26/14. // Copyright (c) 2014 Ray Wenderlich Tutorials. All rights reserved. // #import "RWStoryUploadTaskViewController.h" #warning THIS IS WHERE YOU SET YOUR PARSE.COM API KEYS // see : http://www.raywenderlich.com/19341/how-to-easily-create-a-web-backend-for-your-apps-with-parse // https://parse.com/tutorials static NSString const *kAppId = @"YOUR_APP_KEY"; static NSString const *kRestApiKey = @"YOUR_REST_API_KEY"; @interface RWStoryUploadTaskViewController () @property (weak, nonatomic) IBOutlet UITextField *story; @end @implementation RWStoryUploadTaskViewController #pragma mark Private - (IBAction)postStory:(id)sender { // 1 NSURL *url = [NSURL URLWithString:@"https://api.parse.com/1/classes/FishStory"]; NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; // Parse requires HTTP headers for authentication. Set them before creating your NSURLSession [config setHTTPAdditionalHeaders:@{@"X-Parse-Application-Id":kAppId, @"X-Parse-REST-API-Key":kRestApiKey, @"Content-Type": @"application/json"}]; NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; // 2 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; request.HTTPMethod = @"POST"; // 3 NSDictionary *dictionary = @{@"story": self.story.text}; NSError *error = nil; NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&error]; if (!error) { // 4 NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // Check to make sure the server didn't respond with a "Not Authorized" if ([response respondsToSelector:@selector(statusCode)]) { if ([(NSHTTPURLResponse *) response statusCode] == 401) { dispatch_async(dispatch_get_main_queue(), ^{ // Remind the user to update the API Key UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"API Key Needed" message:@"Check the Parse App and Rest API keys in RWStoryUploadTaskViewController.m" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; return; }); } } if (!error) { // Data was created, we leave it to you to display all of those tall tales! dispatch_async(dispatch_get_main_queue(), ^{ self.story.text = @""; }); } else { NSLog(@"DOH"); } }]; // 5 [uploadTask resume]; } } @end
參考链接:http://www.raywenderlich.com/67081/cookbook-using-nsurlsession
使用NSURLSession进行上传下载
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。