2016-10-13 174 views
0

我想要一個例子來理解如何使用目標C中的NSURLSession進行「GET」請求以及如何獲得響應?NSURLSession請求和響應

+0

有幾十這個問題 –

+0

https://www.raywenderlich.com/110458/nsurlsession-tutorial-getting-started –

+0

爵士提供的答案,我使用目標C 。請建議一些教程,解釋如何在目標c中使用NSURLSession從服務器獲取「GET」請求並獲取響應。 – FreshStar

回答

2

GET

NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"give your url here"]]; 

//create the Method "GET" 
[urlRequest setHTTPMethod:@"GET"]; 

NSURLSession *session = [NSURLSession sharedSession]; 

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 
{ 
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 
    if(httpResponse.statusCode == 200) 
    { 
    NSError *parseError = nil; 
    NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError]; 
    NSLog(@"The response is - %@",responseDictionary); 
    } 
    else 
    { 
    NSLog(@"Error");  
    } 
}]; 
[dataTask resume];