将数据发送到 3D Touch 快捷方式

Sending data to 3D Touch shortcut

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

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

您应该为包含该项目的数组创建一个 UIApplicationShortcutItem with its title set to the weather conditions you want to show, then set your application’s shortcutItems。例如:

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

请注意,“type”参数是一个任意字符串——您的应用委托只需要能够在用户 selects the shortcut.

时识别它