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



我试图在Swift 4中的iPhone和Apple Watch应用程序之间传递一个数组,但到目前为止我没有成功。以下是我尝试过的几个例子,但没有成功。在这些例子中,它们不包括很多函数,但是,当我尝试这样写它时,它会给出错误does not conform to protocols。此外,当我声明监视会话时,它没有正确声明,而且swift 4中的didRecieveApplicationContext与其他问题/例子Link Link2 中所示的非常不同

这是我的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控制器

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有关的文件,因此,如果能提供任何帮助,我们将不胜感激。

WKInterfaceController:中

我同意Jens Peter的评论,即不应该将didReceiveApplicationContext封装在load()函数中。

按如下方式处理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?,并将awake(withContext)中的WCSession声明为:

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

同时删除对awake(withContext)load()的调用。

InterfaceController中,将一些print语句放在WCSession存根中是很有帮助的,即使您没有完全使用它们。您可以看到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)")
}

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

按照在WKInterfaceController中所做的操作卸下var watchSession: WCSession?。在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)
}
}  
}

我认为这会稍微清理一下,希望能起作用,或者至少能推动你前进。然而,我并没有在项目中构建它。希望这能有所帮助。

最新更新