【发布时间】:2017-10-19 00:42:25
【问题描述】:
我试图在 Swift 4 中的 iPhone 和 Apple Watch 应用程序之间传递一个数组,到目前为止我一直没有成功。以下是我尝试遵循的一些示例,但均未成功。在这些示例中,它们不包含许多功能,但是当我尝试像这样编写它时,它会给出错误does not conform to protocols,此外,当我声明监视会话时它没有正确声明,didRecieveApplicationContext 也是在 swift 4 中与其他问题/示例中显示的非常不同 Link Link2
这是我的 iPhone 视图控制器
import UIKit
import WatchConnectivity
class watchtimetablemaker: UIViewController, WCSessionDelegate {
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
}
func sessionDidBecomeInactive(_ session: WCSession) {
}
func sessionDidDeactivate(_ session: WCSession) {
}
var watchSession: WCSession?
var initalArray = [String]()
var combination = ""
var vdlArray = [String]()
@IBAction func Save(_ sender: Any) {
vdlArray.removeAll()
//here I edit the arrays, add instances etc. cut out for fluency
self.view.endEditing(true)
sendToWatch()
UserDefaults.standard.set(vdlArray, forKey: "vdlarray")
UserDefaults.standard.synchronize()
print(initalArray)
print(vdlArray)
}
func sendToWatch(){
do{
let appDictionary = ["Array": initalArray]
try WCSession.default.updateApplicationContext(appDictionary)
}
catch {
print(error)
}
}
override func viewDidLoad() {
super.viewDidLoad()
if (WCSession.isSupported()){
watchSession = WCSession.default
watchSession?.delegate = self
watchSession?.activate()
}
vdlArray = UserDefaults.standard.array(forKey: "vdlarray") as! [String]
print(vdlArray)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
这是 Apple Watch 控制器
import WatchKit
import Foundation
import WatchConnectivity
class TimetableWatch: WKInterfaceController, WCSessionDelegate {
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
load()
}
@IBOutlet var tabletitle: WKInterfaceTable!
var watchSession: WCSession?
var tableData = [String]()
override func awake(withContext context: Any?) {
super.awake(withContext: context)
if (WCSession.isSupported()){
watchSession = WCSession.default
watchSession?.delegate = self
watchSession?.activate()
}
load()
tabletitle.setNumberOfRows(tableData.count, withRowType: "Cell")
var i = 0
for item in tableData {
let row = tabletitle.rowController(at: i) as! TableCellRow
row.tbalecelllabel.setText(item)
i = i + 1
}
}
func load(){
func session(session: WCSession, didRecieveApplicationContext applicationContext: [String : Any]) {
DispatchQueue.main.async() { () -> Void in
if let retreivedArray = applicationContext["Array"] as? [String] {
self.tableData = retreivedArray
print(self.tableData)
}
}
}
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
}
我无法找到任何与 swift4 相关的文档,因此,我们将不胜感激。
【问题讨论】:
-
我还没有使用过 Swift 4,但是你的 didReceiveApplicationContext 函数被包装在 load() 函数中看起来很奇怪。您可以像这样声明 WCSession:let session = WCSession.default()
标签: arrays watchkit swift4 watchconnectivity