2015-11-14 2 views
7

Я просматривал примеры в WatchOS 2 По учебнику книги, написанной командой RayWenderlich, в частности главе 18. Все они работают нормально. В моем собственном приложении я пытаюсь отправить кнопку с часами, чтобы запустить кнопку в приложении iPhone. Вот соответствующий код в Swift с вахты и телефона:Отладочный совет для WatchOS2

Смотреть:

// 
// InterfaceController.swift 
// Wasted Time Extension 
// 
// Created by Michael Rowe on 7/21/15. 
// Copyright © 2010-2015 Michael Rowe. All rights reserved. 
// 

import WatchKit 
import WatchConnectivity 
import Foundation 


class InterfaceController: WKInterfaceController,WCSessionDelegate { 

    @IBOutlet var wasteLabel: WKInterfaceLabel! 
    @IBOutlet var costLabel: WKInterfaceLabel! 
    @IBOutlet var counter: WKInterfaceLabel! 
    @IBOutlet var statusButton: WKInterfaceButton! 

    // our watchconnective session 
    var session : WCSession? 


    override func awakeWithContext(context: AnyObject?) { 
     super.awakeWithContext(context) 
    } 

    override func willActivate() { 
     // This method is called when watch view controller is about to be visible to user 
     super.willActivate() 

     if(WCSession.isSupported()){ 
      session = WCSession.defaultSession() 
      session!.delegate = self 
      session!.activateSession() 
     } 
    } 

    override func didDeactivate() { 
     // This method is called when watch view controller is no longer visible 
     super.didDeactivate() 
    } 

    func session(session: WCSession, didReceiveMessage message: [String: AnyObject], replyHandler: [String: AnyObject] -> Void) { 

     print("Did receive message Watch \(message)") 
    } 

    @IBAction func addButtonPressed() { 

     // Pull values from the Phone for current meeting cost, waste costs, and people in meeting 
     let prefs:NSUserDefaults = NSUserDefaults(suiteName: "a.b.c")! 

     var counterd = prefs.doubleForKey("keyPeopleInMeeting") 


     counterd++ 
     counter.setText(String(format:"%9.0f", counterd)) 

     // Sending data to iPhone via Interactive Messaging 
     if WCSession.isSupported(){ 
      // we have a watch supporting iPhone 

      let session = WCSession.defaultSession() 

      // we can reach the watch 
      if session.reachable { 
       let message = ["add": "1"] 
       print("Message \(message)") 
       session.transferUserInfo(message) 
       print("Send Message Add - People \(counterd)") 
      } 
     } 

     if WCSession.isSupported() { 
      let session = WCSession.defaultSession() 
      if session.reachable { 
      let message = ["add":"1"] 
      session.sendMessage(message, replyHandler: { (reply: [String: AnyObject]) -> Void in 
      print("Reply: \(reply)") 
      }, errorHandler: { (error: NSError) -> Void in 
      print("ERROR Watch: \(error.localizedDescription)") 
      }) 
     } else { // reachable 
      self.showReachabilityError() 
      } 
     } 

     print("Watch Add Button Pressed \(counterd)") 
    } 

    @IBAction func minusButtonPressed() { 
     // Pull values from the Phone for current meeting cost, waste costs, and people in meeting 
     let prefs:NSUserDefaults = NSUserDefaults(suiteName: "a.b.c")! 

     var counterd = prefs.doubleForKey("keyPeopleInMeeting") 
     counterd-- 
     if (counterd <= 1) { 
      counterd = 1 
     } 
     counter.setText(String(format:"%9.0f", counterd)) 

     if WCSession.isSupported() { 
      let session = WCSession.defaultSession() 
      if session.reachable { 
       let message = ["minus":"1"] 
      session.sendMessage(message, replyHandler: { (reply: [String: AnyObject]) -> Void in 
      print("Reply: \(reply)") 
      }, errorHandler: { (error: NSError) -> Void in 
      print("ERROR Watch: \(error.localizedDescription)") 
      }) 
      } else { // reachable 
       self.showReachabilityError() 
      } 
     } 

     print("Watch Minus Button Pressed \(counterd)") 
} 

    func statusButtonPressed() { 
     // Pull values from the Phone for current meeting cost, waste costs, and people in meeting 
     let prefs:NSUserDefaults = NSUserDefaults(suiteName: "a.b.c")! 

     let status = statusButton.description 

     if WCSession.isSupported() { 
      let session = WCSession.defaultSession() 
      if session.reachable { 
      let message = ["status":status] 
      session.sendMessage(message, replyHandler: { (reply: [String: AnyObject]) -> Void in 
      print("Reply: \(reply)") 
      }, errorHandler: { (error: NSError) -> Void in 
      print("ERROR Watch: \(error.localizedDescription)") 
      }) 
     } else { // reachable 
      self.showReachabilityError() 
      } 
     } 

     print("Watch Status Button Pressed - Status \(statusButton)") 
    } 

    func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]){ 

     let prefs:NSUserDefaults = NSUserDefaults(suiteName: "a.b.c")! 

     if let waste = applicationContext["waste"] as? Float { 
      print("Watch Receive - Waste \(waste)") 
     } 

     if let cost = applicationContext["cost"] as? Float { 
      print("Watch Receive - Cost \(cost)") 
     } 

     if let counternum = applicationContext["counter"] as? Float { 
      print("Watch Receive - Counter \(counternum)") 
     } 

     if let status = applicationContext["status"] as? String { 
      print("Watch Receive - Status \(status)") 
      statusButton.setTitle(status) 
     } 

    } 

    private func showReachabilityError() { 
      let tryAgain = WKAlertAction(title: "Try Again", style: .Default, handler: {() -> Void in }) 
      let cancel = WKAlertAction(title: "Cancel", style: .Cancel, handler: {() -> Void in }) 
      self.presentAlertControllerWithTitle("Your iPhone is not reachable.", message: "You cannot adjust the status or number of attendees Watch is not currently connected to your iPhone. Please ensure your iPhone is on and within range of your Watch.", preferredStyle: WKAlertControllerStyle.Alert, actions:[tryAgain, cancel]) 
    } 

    func session(session: WCSession, didFinishUserInfoTransfer userInfoTransfer: WCSessionUserInfoTransfer, error: NSError?) { 

     print("Transfer User Info Error watch: \(error)") 
    } 

} 

и получающий код на iPhone: КОД:

func session(session: WCSession, 
    didReceiveMessage message: [String : AnyObject], 
    replyHandler: ([String : AnyObject]) -> Void) { 

    if let counterd = message["add"] as? Float { 
     let reply = ["add":counterd] 
     print("iPhone Receive Add \(counterd)") 
     addButtonPressed(self) 
     replyHandler(reply) 
    } 

    if let counterd = message["minus"] as? Float { 
     let reply = ["minus":counterd] 
     print("iPhone Receive minus \(counterd)") 
     removeButtonPressed(self) 
     replyHandler(reply) 
    } 

    if let status = message["status"] as? String { 
     if status == "Start" { 
      let reply = ["status":"Quorum"] 
      meetingStartedButtonPressed(self) 
      replyHandler(reply) 
     } 
     if status == "Quorum" { 
      let reply = ["status": "Finish"] 
      quorumButtonPressed(self) 
      replyHandler(reply) 
     } 
     if status == "Finish" { 
      let reply = ["status": "Reset"] 
      meetingEndedButtonPressed(self) 
      replyHandler(reply) 
     } 
     if status == "Reset" { 
      let reply = ["status": "Start"] 
      resetButtonPressed(self) 
      replyHandler(reply) 
     } 
     print("iPhone Received Status Button \(status)") 
    } 
} 

Я получаю сообщение стрельбу штрафа на Watch и посмотреть их в журнале отладки ... Но они, похоже, не срабатывают на телефоне. Телефон успешно отправляет свои сообщения на часы.

Я тестировал этот код как в симуляторе, так и на собственных часах и iPhone. Обратите внимание, что сообщения с iPhone на Watch выполняются с помощью via updateApplicationContext и отправляемого сообщения, которое я пытаюсь использовать для отправки сообщений с часовых телефонов на iPhone. Вот пример кода iPhone для отправки контекста:

 if WCSession.isSupported() { 
     if session.watchAppInstalled { 
      let UserInfo = ["waste":Float((wastedAmount.text! as NSString).floatValue), "cost":Float((totalAmount.text! as NSString).floatValue), "counter":Float((peopleInMeeting.text! as NSString).floatValue), "status":"Start"] 
      do { 
       try session.updateApplicationContext(UserInfo as! [String : AnyObject]) 
      } catch { 
       print("Updating the context failed: ") 
      } 
     } 
    } 
+0

ли приведение к 'Double' успех? Счетчик звучит так, будто это может быть 'Int'? – stkent

+0

Приведение к двойному успеху. –

+0

На стороне часов вы внедрили 'func session (session: WCSession, didFinishUserInfoTransfer userInfoTransfer: WCSessionUserInfoTransfer, ошибка: NSError?)'? Получает ли он какие-либо обратные вызовы с любыми ошибками? – ccjensen

ответ

0

Отладка в Watch-OS во время работы приложения iPhone и наоборот в Xcode-8.1. Требуемый хост Процесс необходимо подключить.

Визуально: -

enter image description here

2

требуется больше информации относительно конкретно, что вы на самом деле видим на Дозоре, когда вы говорите:

I get the messages firing fine on the Watch and see them in the debug log... But they do not seem to fire on the Phone. The phone is successfully sending its messages to the watch.

Однако один обычное явление что код iPhone действительно работает правильно, и единственное, что вы не видите, - это отладочные заявления, напечатанные на консоли. Вероятно, это так, потому что вы говорите, что видите ожидаемые сообщения «Вахта», предположительно включая те, что указаны от print("Reply: \(reply)"). Это означает, что сообщение обрабатывается iPhone.

В этом случае часто бывает просто, что вы ожидаете увидеть сообщения консоли отладки одновременно с процессами симулятора Watch и iOS, но на самом деле вы подключены только к одному или другому. Есть (по крайней мере) две вещи, которые вы можете сделать здесь:

  1. Запустите приложение WatchKit с Xcode, но затем измените его на прикрепление к процессу iPhone. В Xcode зайдите Debug > Attach to Process... и выберите приложение iPhone в разделе «Вероятные цели».
  2. Начните с запуска приложения iPhone, что означает, что вы уже привязаны к этому процессу. В симуляторе Apple Watch запустите приложение Watch. Затем вы сможете отлаживать iPhone на стороне связи.
Смежные вопросы