0

我正在构建一个天气应用程序,我希望能够在用户激活快捷菜单(通过主屏幕上的 3D Touch)时看到天气数据(例如温度)。我希望天气数据显示在快捷方式中,这样用户就不必进入应用程序来检查温度。这是用于检索天气数据的代码,如果需要,我将发布更多代码:

struct ForecastService {
  let forecastAPIKey: String
  let forecastBaseURL: NSURL?
  init(apiKey: String) {
    forecastAPIKey = apiKey
    forecastBaseURL = NSURL(string: "https://api.forecast.io/forecast/\(forecastAPIKey)/")
  }

  func getForecast(lat: Double, long: Double, completion: (CurrentWeather? -> Void)) {
    if let forecastURL = NSURL(string: "\(lat),\(long)", relativeToURL: forecastBaseURL) {
        let networkOperation = NetworkOperation(url: forecastURL)

        networkOperation.downloadJSONFromURL {
            (let JSONDictionary) in
            let currentWeather = self.currentWeatherFromJSON(JSONDictionary)
            completion(currentWeather)
        }
    } else {
        print("Could not construct a valid URL")
    }
  }

  func currentWeatherFromJSON(jsonDictionary: [String: AnyObject]?) -> CurrentWeather? {
    if let currentWeatherDictionary = jsonDictionary?["currently"] as? [String: AnyObject] {
        return CurrentWeather(weatherDictionary: currentWeatherDictionary)
    } else {
        print("JSON Dictionary returned nil for 'currently' key")
        return nil
    }
  }
}//end struct
4

1 回答 1

3

您应该创建一个UIApplicationShortcutItem,并将其标题设置为您要显示的天气条件,然后将您的应用程序的shortcutItems设置为包含该项目的数组。例如:

let item = UIApplicationShortcutItem(type:"showCurrentConditions", localizedTitle:"64° Sunny")
UIApplication.sharedApplication().shortcutItems = [item]

请注意,“type”参数是一个任意字符串——您的应用程序代理只需要在用户选择快捷方式时能够识别它。

于 2015-12-08T23:31:25.533 回答