从iPhone传递字符串

时间:2015-09-24 23:56:07

标签: ios swift cloudkit watch-os-2

我尝试传递我的CloudKit数据库中找到的每个color Play

iPhone - >观看

iOS TableViewController

func getCloudKit() {
    ///...
    let publicData = container.publicCloudDatabase
    publicData.performQuery(query, inZoneWithID: nil) { results, error in
        if error == nil { // There is no error
            for play in results! {
                let newPlay = Play()
                do {
                    try WatchSessionManager.sharedManager.updateApplicationContext(["color" : newPlay.teamColor])
                    NSLog("NewPColor: %@", newPlay.teamColor)
                } catch {
                    print(error)
                }
                self.objects.append(newPlay)
            }
        } else {
            print(error)
        }
    }
}

当我NSLog在iOS方面传递的内容时,它完美记录3 color s

2015-09-25 21:10:28.706 Play[16444] NewPColor: FDB927
2015-09-25 21:10:28.707 Play[16444] NewPColor: 000000
2015-09-25 21:10:28.708 Play[16444] NewPColor: 000000

但是当我进入Watch侧时, colorLabel 中没有显示任何内容。 (我不确定setText是否会被调用,因为"来自iPhone"甚至不会出现。)

WatchKit InterfaceController

func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
    let colorWatch = applicationContext["color"] as? String

    dispatch_async(dispatch_get_main_queue()) {
        if let colorWatch = colorWatch {
            self.colorLabel.setText("From iPhone: \(colorWatch)")
        }
    }
}

有什么想法吗?可以根据需要发布任何额外的代码,请告诉我。谢谢!

编辑:这里的每个问题都是我的WCSession代码

iOS WatchSessionManager

class WatchSessionManager: NSObject, WCSessionDelegate {

    static let sharedManager = WatchSessionManager()
    private override init() {
        super.init()
    }

    private let session: WCSession? = WCSession.isSupported() ? WCSession.defaultSession() : nil

    private var validSession: WCSession? {

        if let session = session where session.paired && session.watchAppInstalled {
            return session
        }
        return nil
    }

    func startSession() {
        session?.delegate = self
        session?.activateSession()
    }
}

extension WatchSessionManager {

    // Sender
    func updateApplicationContext(applicationContext: [String : AnyObject]) throws {
        if let session = validSession {
            do {
                try session.updateApplicationContext(applicationContext)
            } catch let error {
                throw error
            }
        }
    }

    // Receiver
    func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
        // handle receiving application context

        dispatch_async(dispatch_get_main_queue()) {
            // make sure to put on the main queue to update UI!
        }
    }
}

1 个答案:

答案 0 :(得分:1)

N.B。您在appContext字典中传递'newPlay',但在日志中打印'newPlayoff'。

我在其他地方推测你已经设置了WCSession委托并调用了activateSession