如何使用Watch Connectivity传输UIImage

如何通过WatchConnecitivity将iPhone上的UIImage传输到Apple Watch上,而不需要用户在手机上进行交互操作,只需加载,因为手表以编程方式调用。 我需要这个,因为创buildUIImage的image processing使用逻辑在Watchkit API中不可用,所以它必须从手机创build。 我看到一些使用Watch连接的例子:

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

不过,我一般都是看新手套装和iOS的,并且对如何使用这个会话pipe理器感到困惑,尤其是从手表到设备,而不是像我在网上的例子中看到的那样。 有人可以提供一个例子,如何在手表和手机上做到这一点,从手表的电话呼叫UIImage

要在iPhone和Apple Watch之间传输文件,应使用Watch Connectivity,使用WCSession正确处理通信。 您可以使用WCSessionDelegate委托方法将UIImage作为NSData发送。

你应该知道的第一件事是将你的UIImage转换为NSData ,反之亦然。 你可以使用下面的代码:

如果PNG图像

 let image = UIImage(named: "nameOfYourImage.jpg") let data = UIImagePNGRepresentation(image) 

如果JPG图像

 let image = UIImage(named: "nameOfYourImage.jpg") let data = UIImageJPEGRepresentation(image, 1.0) 

然后你可以使用WCSession来发送消息,如下所示:

ViewController.swift

 class ViewController: UIViewController, WCSessionDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if WCSession.isSupported() { WCSession.defaultSession().delegate = self WCSession.defaultSession().activateSession() } let image = UIImage(named: "index.jpg")! let data = UIImageJPEGRepresentation(image, 1.0) WCSession.defaultSession().sendMessageData(data!, replyHandler: { (data) -> Void in // handle the response from the device }) { (error) -> Void in print("error: \(error.localizedDescription)") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 

InterfaceController.swift

 import WatchKit import Foundation import WatchConnectivity class InterfaceController: WKInterfaceController, WCSessionDelegate { 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() { WCSession.defaultSession().delegate = self WCSession.defaultSession().activateSession() } } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } func session(session: WCSession, didReceiveMessageData messageData: NSData, replyHandler: (NSData) -> Void) { guard let image = UIImage(data: messageData) else { return } // throw to the main queue to upate properly dispatch_async(dispatch_get_main_queue()) { [weak self] in // update your UI here } replyHandler(messageData) } } 

在上面的代码中,当你打开ViewController它发送的是UIImage ,上面的例子只是为了学习的目的,你必须以一个更加适当的方式处理它,关于你的项目的复杂性。

我希望这可以帮助你。

你必须把你的图像转换为NSData,然后在手表上进行解码。 你可以看看我的博客文章,我介绍了类似的情况。 http://eluss.github.io/AppleWatch_iPhone_data_transfer/

这不是会话的方式,因为当时我还没有意识到这一点,但也许它会帮助你获得整个逻辑。