oc-网络请求

oc-网络请求_第1张图片
图片发自App

网络请求是编程的重要一步份
///

  • (void)getDataWith: (NSString *)URLString{

    NSURL * url = [NSURL URLWithString:URLString];
    //网络请求对象
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    NSURLSession * session = [NSURLSession sharedSession];
    //请求任务
    NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    //主线程
    dispatch_async(dispatch_get_main_queue(), ^{
    //解析json数据
    if (!error) {
    id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"result = %@",result);
    for (NSDictionary * songDic in result) {
    Song * song = [[Song alloc]init];
    [song setValuesForKeysWithDictionary:songDic];
    [self.songArr addObject:song];
    }
    //刷新tableview的数据
    [self.tableView reloadData];
    } else {
    NSLog(@"error : %@",error);
    }
    });
    }];
    //手动开启任务
    [dataTask resume]
    }
    ///

你可能感兴趣的:(oc-网络请求)