2015-12-08 65 views
0

我正在構建天氣應用程序,並希望在用戶激活快捷菜單(通過主屏幕上的3D Touch)時看到天氣數據(例如溫度)。我希望天氣數據顯示在快捷方式中,因此用戶不必輸入應用程序來檢查溫度。下面是用來檢索天氣數據的代碼,我會發布更多的代碼,如果需要的話:將數據發送到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 

回答

3

您應該創建它的標題設置爲你想要顯示的天氣條件UIApplicationShortcutItem,然後設置應用程序的shortcutItems到包含該項目的數組。例如:

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

注意「類型」參數是一個任意的字符串,你的應用程序代理只需要能夠識別它,當用戶selects the shortcut