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

时间:2015-12-08 19:42:27

标签: swift swift2 3dtouch

我正在构建天气应用程序,我希望能够在用户激活快捷菜单时(通过主屏幕上的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

1 个答案:

答案 0 :(得分:3)

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

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

请注意,“type”参数是一个任意字符串 - 您的app委托只需要能够在用户selects the shortcut时识别它。