[英]Apple Watch, WatchKit Extension and main application
有帶有邏輯的主要應用程序,我們將應用程序擴展到 Apple Watch。
添加目標 xCode 后,創建了另外 2 個應用程序:代碼擴展和手表套件應用程序。
問題:擴展中的代碼如何重用准備好的和已經制作的主 iOS 應用程序的邏輯? 擴展應用程序如何與主應用程序通信並發送命令。
要與包含的 iPhone 應用程序通信,您可以使用
(BOOL)openParentApplication:(NSDictionary *)userInfo
reply:(void (^)(NSDictionary *replyInfo,
NSError *error))reply
在你的WKInterfaceController
來自 Apple 文檔
使用此方法與包含的 iOS 應用程序進行通信。 調用該方法會導致 iOS 在后台啟動應用程序(根據需要)並調用
application:handleWatchKitExtensionRequest:reply
: 其應用程序委托的方法。 該方法具有以下簽名:
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo
reply:(void(^)(NSDictionary *replyInfo))reply
應用程序委托接收您傳遞給 userInfo 參數的字典,並使用它來處理您提出的任何請求。 如果它提供回復,WatchKit 會執行您在此方法的回復參數中提供的塊。
在 Apple Watch Extension 的當前狀態下:
您可以在 iOS 主應用程序和 WatchKit 擴展程序之間共享信息。 使用 App Groups 和 NSUserDefaults 訪問共享信息對象。
您無法從 Apple Watch 上的操作觸發的 iOS 應用程序中執行代碼。
至少現在還沒有。
編輯:從 Xcode 6.2 Beta 2 開始
現在可以從 Apple Watch 與父 iOS 應用程序通信。
在 WatchKit 擴展中,通過openParentAppentApplicion
調用父應用程序。 可以將值字典傳遞給父應用程序,父應用程序可以返回值字典。
Watchkit 擴展:
// Call the parent application from Apple Watch
// values to pass
let parentValues = [
"value1" : "Test 1",
"value2" : "Test 2"
]
WKInterfaceController.openParentApplication(parentValues, reply: { (replyValues, error) -> Void in
println(replyValues["retVal1"])
println(replyVaiues["retVal2"])
})
iOS應用程序:
// in AppDelegate.swift
func application(application: UIApplication!, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!, reply: (([NSObject : AnyObject]!) -> Void)!) {
// retrieved parameters from Apple Watch
println(userInfo["value1"])
println(userInfo["value2"])
// pass back values to Apple Watch
var retValues = Dictionary<String,String>()
retValues["retVal1"] = "return Test 1"
retValues["retVal2"] = "return Test 2"
reply(retValues)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.