• 赚钱入口【需求资源】限时招募流量主、渠道主,站长合作;【合作模式】CPS长期分成,一次推广永久有收益。主动打款,不扣量;

WatchConnectivity实现iPhone与iWatch互相通信

iOS cps12345 2个月前 (11-24) 59次浏览 0个评论

iPhone向iWatch发送数据

  func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { }
  func sessionDidBecomeInactive(_ session: WCSession) { }
  func sessionDidDeactivate(_ session: WCSession) { }

  var session: WCSession?

var count = 0

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    if WCSession.isSupported() {
          session = WCSession.default
          session?.delegate = self
          session?.activate()
      }
}

    @IBAction func addPlusOne(_ sender: UIButton) {
    let count += 1
    let sendHabit = String(count)
    if let validSession = session {
              let iPhoneAppCount = ["Habits": sendHabit]

              do {
                  try validSession.updateApplicationContext(iPhoneAppCount)
              } catch {
                  print("Something went wrong")
              }
          }

接收iWatch的数据:

     let session = WCSession.default

override func awake(withContext context: Any?) {
    super.awake(withContext: context)

       processApplicationContext()
       processApplicationCount()

       session.delegate = self
       session.activate()
}

    func processApplicationCount() {
    if let iPhoneContext = session.receivedApplicationContext as? [String : String] {

        displayLabel.setText(iPhoneContext["Habits"])

    }
}

func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
    DispatchQueue.main.async() {
        self.processApplicationCount()
    }
}

iWatch向iPhone发送数据

可以使用Watch中的WCSession的updateApplicationContext():

let session = WCSession.default()
if session.activationState == .activated {
    session.updateApplicationContext(["my_global": g_myGlobal])
}

然后,在iPhone上,您应该为WCSession分配一个委托并实现以下内容:

func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
    let receivedGlobal = applicationContext["my_global"] as? TypeOfTheGlobal
}
喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址