0

我创建了一个在 iphone 上运行的计时器应用程序。我希望我们能控制它 iPhone 和 Watch

项目截图

iPhone 上的控件(播放、停止、重新启动)工作正常,我的仪表显示在手表上。

Watch on the Stop 效果很好,因为对 Start 不起作用,仪表无法打开 iPhone 或 Watch。

也重新开始工作。

如果信息来自手表,我在 iPhone 上的标签更改非常缓慢,但在另一个方向上运行良好,朝向 iPhone 手表

有没有注意到这个问题,是WatchConnectivity相关的问题

谢谢你的帮助

下面是我的代码:

ViewController.swift

import UIKit
import WatchConnectivity

class ViewController: UIViewController, WCSessionDelegate {

@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var watchLabel: UILabel!

var session: WCSession!
var timerCount = 0
var timerRunning = false
var timer = NSTimer()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    if (WCSession.isSupported()) {
        let session = WCSession.defaultSession()
        session.delegate = self
        session.activateSession()

        if session.paired != true {
            print("Apple Watch is not paired")
        }

        if session.watchAppInstalled != true {
            print("WatchKit app is not installed")
        }
    } else {
        print("WatchConnectivity is not supported on this device")
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}    


@IBAction func startButton(sender: UIButton) {
    startPlay()
}

@IBAction func stopButton(sender: UIButton) {
    stopPlay()
}


@IBAction func restartButton(sender: UIButton) {
   restartPlay()
}

//Receive messages from watch
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
    var replyValues = Dictionary<String, AnyObject>()

    //let viewController = self.window!.rootViewController as! ViewController      
    switch message["command"] as! String {
    case "start" :
        startPlay()
        replyValues["status"] = "Playing"
    case "stop" :
        stopPlay()
        replyValues["status"] = "Stopped"
    case "restart" :
        restartPlay()
        replyValues["status"] = "Stopped"
    default:
        break
    }
    replyHandler(replyValues)
}

//Counter Timer
func counting(timer:NSTimer) {
    self.timerCount++
    self.timerLabel.text = String(timerCount)

    let requestValues = ["timer" : String(timerCount)]
    let session = WCSession.defaultSession()
    session.sendMessage(requestValues, replyHandler: nil, errorHandler: { error in print("error: \(error)")})
}

//Fonction Play
func startPlay() {
    if timerRunning == false {
        self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("counting:"), userInfo: nil, repeats: true)
        self.timerRunning = true
        self.watchLabel.text = "START"
    }
}

//Fonction Stop
func stopPlay() {
    if timerRunning == true {
        self.timer.invalidate()
        self.timerRunning = false
        self.watchLabel.text = "STOP"
    }
}

//Fonction Restart
func restartPlay() {
    self.timerCount = 0
    self.timerLabel.text = "0";

    let requestValues = ["timer" : "0"]
    let session = WCSession.defaultSession()
    session.sendMessage(requestValues, replyHandler: nil, errorHandler: { error in print("error: \(error)")})
}
}

接口控制器.swift

import WatchKit
import Foundation
import WatchConnectivity


class InterfaceController: WKInterfaceController, WCSessionDelegate {

@IBOutlet var watchLabel: WKInterfaceLabel!
@IBOutlet var statusLabel: WKInterfaceLabel!

//Receiving message from iphone
func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
    self.watchLabel.setText(message["timer"]! as? String)
    // self.statusLabel.setText(message["command"]! as? String)
}


override func awakeWithContext(context: AnyObject?) {
    super.awakeWithContext(context)
    // Configure interface objects here.
}

override func willActivate() {
    // This method is called when watch view controller is about to be visible to user
    super.willActivate()
    if (WCSession.isSupported()) {
        let 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()
}


@IBAction func startButtonWatch() {
    if WCSession.defaultSession().reachable == true {
        let requestValues = ["command" : "start"]
        let session = WCSession.defaultSession()
        session.sendMessage(requestValues, replyHandler: { reply in
            self.statusLabel.setText(reply["status"] as? String)
            }, errorHandler: { error in
                print("error: \(error)")
        })

    }

}


@IBAction func stopButtonWatch() {
    if WCSession.defaultSession().reachable == true {
        let requestValues = ["command" : "stop"]
        let session = WCSession.defaultSession()
        session.sendMessage(requestValues, replyHandler: { reply in
            self.statusLabel.setText(reply["status"] as? String)
            }, errorHandler: { error in
                print("error: \(error)")
        })

    }
}

@IBAction func restartButtonWatch() {
    if WCSession.defaultSession().reachable == true {
        let requestValues = ["command" : "restart"]
        let session = WCSession.defaultSession()
        session.sendMessage(requestValues, replyHandler: { reply in
            self.statusLabel.setText(reply["status"] as? String)
            }, errorHandler: { error in
                print("error: \(error)")
        })

    }

}

}
4

2 回答 2

0


你应该使用这个:

   func startPlay() {
    if timerRunning == false {
        //self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("counting:"), userInfo: nil, repeats: true)
        self.timer = NSTimer(timeInterval: 1, target: self, selector: "counting:", userInfo: nil, repeats: true)
        NSRunLoop.mainRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes)
        self.timerRunning = true
        self.watchLabel.text = "Start"
    }
}


我无法解释为什么我们需要明确使用 NSRunLoop。在开发具有数据传输功能的应用程序时,我遇到了相同的计时器问题。您可以通过查询“nstimer 运行循环”或此处在 google 中找到一些答案。
我更喜欢用它来重启:

    func restartPlay() {
    self.timerCount = 0
    self.timerLabel.text = "0";
    stopPlay()
    startPlay()
    self.watchLabel.text = "Restarted"
}


干杯。

于 2015-10-22T13:50:21.703 回答
0

这个功能和优化的代码:

//Fonction Play
func startPlay() {
    if timerRunning == false {
        self.mytimer = NSTimer(timeInterval: 1, target: self, selector: "counting:", userInfo: nil, repeats: true)
        NSRunLoop.mainRunLoop().addTimer(self.mytimer, forMode: NSRunLoopCommonModes)
        timerRunning = true
        dispatch_async(dispatch_get_main_queue()) {
            self.watchLabel.text = "PLAYING"
        }
    }
}
于 2015-10-23T08:04:34.540 回答