我们已经有 Weather 这个 Model 类型了,现在我们需要一个 API Client 来获取这个信息。在 WeatherWatchKit target 中新建一个文件 WeatherClient.swift,并填写以下代码:
import Foundation public let WatchWeatherKitErrorDomain = "com.onevcat.WatchWeatherKit.error" public struct WatchWeatherKitError { public static let CorruptedJSON = 1000 } public struct WeatherClient { public static let sharedClient = WeatherClient() let session = NSURLSession.sharedSession() public func requestWeathers(handler: ((weather: [Weather?]?, error: NSError?) -> Void)?) { guard let url = NSURL(string: "https://raw.githubusercontent.com/onevcat/WatchWeather/master/Data/data.json") else { handler?(weather: nil, error: NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: nil)) return } let task = session.dataTaskWithURL(url) { (data, response, error) -> Void in if error != nil { handler?(weather: nil, error: error) } else { do { let object = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) if let dictionary = object as? [String: AnyObject] { handler?(weather: Weather.parseWeatherResult(dictionary), error: nil) } } catch _ { handler?(weather: nil, error: NSError(domain: WatchWeatherKitErrorDomain, code: WatchWeatherKitError.CorruptedJSON, userInfo: nil)) } } } task!.resume() } }其实我们的 client 现在有点过度封装和耦合,不过作为 demo 来���的话还不错。它现在只有一个方法,就是从网络源请求一个 JSON 然后进行解析。解析的代码 parseWeatherResult 我们放在了 Weather 中,以一个 extension 的形式存在:
// MARK: - Parsing weather request extension Weather { static func parseWeatherResult(dictionary: [String: AnyObject]) -> [Weather?]? { if let weathers = dictionary["weathers"] as? [[String: AnyObject]] { return weathers.map{ Weather(json: $0) } } else { return nil } } }我们在 ViewController 中使用这个方法即可获取到天气信息,就可以构建我们的 UI 了。在 ViewController.swift 中,加入一个属性来存储天气数据:
var data: [Day: Weather]?然后更改 viewDidLoad 的代码:
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. dataSource = self let vc = UIViewController() vc.view.backgroundColor = UIColor.whiteColor() setViewControllers([vc], direction: .Forward, animated: true, completion: nil) UIApplication.sharedApplication().networkActivityIndicatorVisible = true WeatherClient.sharedClient.requestWeathers { (weather, error) -> Void in UIApplication.sharedApplication().networkActivityIndicatorVisible = false if error == nil && weather != nil { for w in weather! where w != nil { self.data[w!.day] = w } let vc = self.weatherViewControllerForDay(.Today) self.setViewControllers([vc], direction: .Forward, animated: false, completion: nil) } else { let alert = UIAlertController(title: "Error", message: error?.description ?? "Unknown Error", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } }