Search code examples
swiftswift23dtouch

Sending data to 3D Touch shortcut


I am building a weather application and I want to be able to have weather data (e.g. Temperature) be seen when a user activates a shortcut menu (via 3D Touch on the home screen). I would like the weather data to show up in the shortcut so the user does not have to enter the application to check the temperature. Here is the code used to retrieve the weather data, I will post more code if need be:

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

Solution

  • You should create a UIApplicationShortcutItem with its title set to the weather conditions you want to show, then set your application’s shortcutItems to an array containing that item. For example:

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

    Note that the “type” parameter is an arbitrary string—your app delegate just needs to be able to recognize it when the user selects the shortcut.