码迷,mamicode.com
首页 > Web开发 > 详细

使用NSURLSession进行上传下载

时间:2017-07-07 10:13:40      阅读:326      评论:0      收藏:0      [点我收藏+]

标签:sync   imageview   tap   nslog   erro   reserve   www   get   date   

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 = %@", jsonDict);
		dispatch_async(dispatch_get_main_queue(), ^{
			self.currentConditionsLabel.text = jsonDict[@"currently"][@"summary"];
			self.tempLabel.text = [jsonDict[@"currently"][@"temperature"]stringValue];
			self.summary.text = jsonDict[@"daily"][@"summary"];
		});
  }
}


@end

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进行上传下载

标签:sync   imageview   tap   nslog   erro   reserve   www   get   date   

原文地址:http://www.cnblogs.com/jzdwajue/p/7130290.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!