ios - NSURLSession 请求和响应

标签 ios objective-c iphone mobile-application

要了解如何在 Objective-C 中使用 NSURLSession 发出 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];

关于ios - NSURLSession 请求和响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40016361/

相关文章:

iphone - iPhone 上的 FFT 可忽略背景噪音并找到更低的音调

iphone - 如何实现 ssl 和 https

ios - AppDelegate 没有可见接口(interface)声明选择器

ios - 合并同名的 NSNotifications

ios - 如何解决这个评分?

iOS 应用被 Apple 拒绝,即使添加了 "Restore Purchase"功能?

ios - 如何返回由一堆异步 HTTP 请求组合而成的对象数组?

iphone - Modal UIViewController 总是在 iPad 上全屏显示。为什么?

iphone - 远程 xml 文件和 uinavigationcontroller、nsurlconnection 放置

ios - 如何使用照片框架快速循环浏览照片库