2016-01-14 51 views
-3

我想要使用NSLog顯示URl的輸出。如何使用NSLog顯示NSURLSession的輸出?

ViewController.h

@interface ViewController : UIViewController{ 
NSURLSession *session; 
NSString *londonWeatherUrl; 
NSURLRequest *request; 
} 

ViewController.m

- (void)viewDidLoad { 
[super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 

londonWeatherUrl = @"http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0"; 

request = [NSURLRequest requestWithURL: 
         [NSURL URLWithString:londonWeatherUrl]]; 


[[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl] 
     completionHandler:^(NSData *data, 
          NSURLResponse *response, 
          NSError *error) {}] resume]; 

session = [NSURLSession sharedSession]; 
NSLog(@"%@",); // what goes here ? 
} 

誰能告訴我,我需要有內部的NSLog什麼,使得URL的輸出顯示在日誌中。 對不起,我在客觀C.

+0

「Url的輸出」 - 你的意思是「迴應」? – Sandr

+0

@Sandr - 是的,響應 –

+0

'NSLog'轉到完成處理程序(在'{'和'}'之間)。你的'data'是完成處理程序的一個參數。您可以以十六進制格式顯示數據,或者您必須先解析它(JSON,UIImage等)。 – Sulthan

回答

1

您可以處理響應呼叫初學者:

- (void)viewDidLoad { 
    [super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 

londonWeatherUrl = @"http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0"; 

request = [NSURLRequest requestWithURL: 
        [NSURL URLWithString:londonWeatherUrl]]; 


[[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl] 
    completionHandler:^(NSData *data, 
          NSURLResponse *response, 
          NSError *error) { 
     // handle response 
     NSLog(@"%@", response); 

}] resume]; 
} 
1

這是你的響應代碼。

- (void)viewDidLoad { 
[super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 

londonWeatherUrl = @"http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0"; 

request = [NSURLRequest requestWithURL: 
         [NSURL URLWithString:londonWeatherUrl]]; 


    [[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl] 
      completionHandler:^(NSData *data, 
           NSURLResponse *response, 
           NSError *error) { 

     NSError* error; 
     NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; //Provide your NSData here to convert to dictionary 

     //NSArray *responses = [json objectForKey:@"YOUR KEY"]; //Provide your key if contain array or else directly use as dictionary 

     NSLog(@"Data dictionary: %@", jsonDictionary); 
     NSLog(@"NSURLResponse: %@", response); 

}] resume]; 

session = [NSURLSession sharedSession];  

} 
+0

如何訪問completionHandler塊之外的響應? – Sandr

+0

@Sandr - 感謝糾正好友 – nikhil84