NSURLSession简单使用(日后补充)

本文介绍了一个使用NSURLSessionDataTask从远程API获取指定地点当前天气信息的方法。通过构造包含位置参数的URL,利用NSURLSession发送请求,并在回调中解析返回的数据。为了确保UI更新在主线程进行,采用了performSelectorOnMainThread方法。

NSURLSessionDataTask

-(void)getTheWeatherInformationOfLocation:(NSString*)location
    {
        NSString *stringUrl = [NSString stringWithFormat:@"https://api.seniverse.com/v3/weather/now.json?key=evhyrbftrsijy35v&location=%@&language=zh-Hans&unit=c",location];
        NSURL * url = [NSURL URLWithString:stringUrl];
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask * dataTask = [session dataTaskWithURL:url
                completionHandler:^(NSData *data,
                                    NSURLResponse *response,
                                    NSError *error) {
                    // handle response
                    myWeatherModel = [WeatherModel initWithDate:data];
                    //由于NSURLSession会另起线程,所以正常来说是不可以在这里直接主线程view reload,而由于网络是有些许延迟的,所以只在主线程code里view reload也是会导致reload的是上一次的结果,所以可以在这里调回主线程并触发reload
                    [self performSelectorOnMainThread:@selector(showWeatherOfLocation) withObject:NULL waitUntilDone:YES];

                    NSLog(@"inside weather is %@",myWeatherModel.weather);

                }];
          //需要调用resume来执行
        [dataTask resume];

    }
-(void)showWeatherOfLocation
{
    self.location.text = location;
    self.weather.text = myWeatherModel.weather;
    self.viewWindow.text = myWeatherModel.name;

    NSLog(@"outside weather is %@",myWeatherModel.weather);
    //reload view,数据更新时用
    [self.view reloadInputViews];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值