要在iPhone和Apple Watch之间传输文件,您应该使用Watch
Connectivity,
WCSession以正确处理通信。您可以使用的委托方法发送
UIImageas
。
NSData``didReceiveMessageData``WCSessionDelegate
您应该知道的第一件事是将您转换
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 = selfWCSession.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 WatchKitimport Foundationimport WatchConnectivityclass 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 = selfWCSession.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,上面的示例仅出于学习目的,您必须以更适当的方式处理项目的复杂性。
希望对您有所帮助。



