updateWeatherAtLocationlocation forNumberOfDaysnumberparameters dictionary]; stringWithFormat,number; stringWithFormat,location.coordinate.latitude,location.coordinate.longitude; forKey; forKey; parameters:parameters successself.delegate respondsToSelectorweatherHTTPClientself.delegate weatherHTTPClient:self didUpdateWithWeather:responseObject]; } failureself.delegate respondsToSelectorweatherHTTPClientself.delegate weatherHTTPClient:self didFailWithError:error]; }]; }
这个方法调用World Weather Online接口,以获得具体位置的天气信息。
非常重要!本实例中的API key仅仅是为本文创建的。如果你创建了一个程序,请在创建一个账号,并获得你自己的API key!
一旦对象获得了天气数据,它需要一些方法来通知对此感兴趣的对象:数据回来了。这里要感谢WeatherHttpClientDelegate 协议和它的delegate方法,在上面代码中的success 和 failure blocks可以通知一个controller:指定位置的天气已经更新了。这样,controller就可以对天气做更新显示。
现在,我们需要把这些代码片段整合到一起!WeatherHTTPClient希望接收一个位置信息,并且WeatherHTTPClient定义了一个delegate协议,现在对WTTableViewControlle类做一下更新,以使用WeatherHTTPClient.
打开WTTableViewController.h 添加一个import,并用下面的代码替换@interface声明:
#import "WeatherHTTPClient.h" @interface WTTableViewController : UITableViewController
另外添加一个新的Core Location manager 属性:
@property(strong) CLLocationManager *manager;
在 WTTableViewController.m中,将下面的代码添加到viewDidLoad:的底部:
self.manager CLLocationManager alloc] init]; self.manager.delegate = self;
上面这两行代码初始化了Core Location manager,这样当view加载的时候,用来确定用户的当前位置。Core Location然后会通过delegate回调以传回位置信息。将下面的方法添加到实现文件中:
locationManagermanager didUpdateToLocationnewLocation fromLocationoldLocation{ newLocation.timestamp timeIntervalSinceNowself.manager stopUpdatingLocation]; WeatherHTTPClient *client = [WeatherHTTPClient sharedWeatherHTTPClient]; client.delegate = self; ; } }
现在,当用户的位置有了变化时,你就可以使用WeatherHTTPClient单例来请求当前位置的天气信息。
记住,WeatherHTTPClient有两个delegate方法需要实现。将下面两个方法添加到实现文件中:
weatherHTTPClientclient didUpdateWithWeatheraWeather{ self.weather = aWeather; self.title ; [self.tableView reloadData]; } weatherHTTPClientclient didFailWithErrorerror{ UIAlertView UIAlertView allocmessagestringWithFormat,error] delegate:nil cancelButtonTitleotherButtonTitles; [av show]; }
上面的两个方法,当WeatherHTTPClient请求成功, 你就可以更新天气数据并重新加载table view。如果网络错误,则显示一个错误信息。
找到apiTapped: 方法,并用下面的方法替换:
sender{ [self.manager startUpdatingLocation]; }
生成并运行程序,点击AP按钮以初始化一个WeatherHTTPClient 请求, 然后会看到如下画面:
希望在这里你未来的天气跟我的一样:晴天! 我还没有死!
你可能注意到了,这里调用的外部web service需要花费一些时间才能返回数据。当在进行网络操作时,给用户提供一个信息反馈是非常重要的,这样用户才知道程序是在运行中或已奔溃了。
在 WTAppDelegate.m中,找到application:didFinishLaunchingWithOptions: 方法,并用下面的方法替换:
applicationapplication didFinishLaunchingWithOptionslaunchOptions ; return YES; }
让sharedManager可以自动的显示出网络活动指示器( network activity indicator)— 无论射门时候,只要有一个新的网络请求在后台运行着。 这样你就不需要每次请求的时候,都要单独进行管理。