WatchConnectivity,如何在iPhone和Apple Watch之间共享阵列

时间:2017-10-19 00:42:25

标签: arrays watchkit swift4 watchconnectivity

我试图在Swift 4中的iPhone和Apple Watch应用程序之间传递一个数组,到目前为止我没有成功。以下是我试图遵循的几个例子,但没有成功。在这些示例中,它们不包含许多函数,但是当我尝试编写它时,它会在我声明监视会话时发出错误does not conform to protocols它没有正确声明,此外,didRecieveApplicationContext在swift 4中与其他问题/示例[{3}} Link

中显示的完全不同

这是我的iPhone ViewController

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 Controller

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相关的文档,所以,我们将非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

WKInterfaceController

我同意Jens Peter的评论,你不应该在load()函数中包含didReceiveApplicationContext

处理activationDidCompleteWith中的错误:

func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
    if let error = error {
        print("Activation failed with error: \(error.localizedDescription)")
        return
    }
    print("Watch activated with state: \(activationState.rawValue)")
}

这也有助于确定WatchConnectivity是否已成立。

完全删除var watchSession: WCSession?并在WCSession中声明awake(withContext)为:

if WCSession.isSupported() {
        let watchSession = WCSession.default
        watchSession = self
        watchSession()
    }

同时取消load()中对awake(withContext)的号召。

InterfaceController中,即使您没有完全使用它们,也可以在WCSession存根中添加一些print语句。您可以看到WatchConnectivity是否正在激活。

func sessionDidBecomeInactive(_ session: WCSession) {
    // To support multiple watches.
    print("WC Session did become inactive.")
}

func sessionDidDeactivate(_ session: WCSession) {
    // To support multiple watches.
    WCSession.default.activate()
    print("WC Session did deactivate.")
}

func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
    if let error = error {
        print("WC Session activation failed with error: \(error.localizedDescription)")
        return
    }
    print("Phone activated with state: \(activationState.rawValue)")
}

您在WCSession.default.activate()中看到的这一行sessionDidDeactivate将允许多个手表支持,如果用户碰巧有多个手表。

var watchSession: WCSession?中一样删除WKInterfaceController。再次通过viewDidLoad()检查WCSession支持:

if WCSession.isSupported() {
        let watchSession = WCSession.default
        watchSession = self
        watchSession()
    }

sendToWatch()更新为:

func sendToWatch() {
let session = WCSession.default()

if session.activationState == .activated {
    let appDictionary = ["Array": initalArray]
do { 
    try session.updateApplicationContext(appDictionary)
} catch {
    print(error)
  }
 }  
}

我认为这会清理一下,希望能够起作用或至少让你前进。但是我没有在一个项目中构建它。希望这可以帮助。