NSURLConection的使用

来源:互联网 发布:2012年西部决赛数据 编辑:程序博客网 时间:2024/06/03 21:03

使用步骤

  1. 创建一个URL
  2. 创建请求
  3. 发送请求
  4. 解析数据

    • iOS9.0 之后,开始需要网络权限,而不是XCode7.0 ,因为XCode7.0默认是9.0的项目,如果改成8.0的项目就美问题了

    • 事例代码

- (void)loadData{    //1.创建 URL    NSURL* url = [NSURL URLWithString:@"http://localhost/demo.json"];    //2.创建请求    NSURLRequest* request = [NSURLRequest requestWithURL:url];    //3.创建连接并发送异步请求    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse* _Nullable response, NSData* _Nullable data, NSError* _Nullable connectionError) {        if (connectionError == nil) {            //4.解析数据            JSONDecoder* decoder = [JSONDecoder decoder];            id jsonString = [decoder objectWithData:data];            NSLog(@"%@", jsonString);        }    }];}
0 0
原创粉丝点击