To transfer files between your iPhone and your Apple Watch you should use Watch Connectivity, using WCSession
to handle the communication properly. You can send an UIImage
as NSData
using the didReceiveMessageData
delegate method of the WCSessionDelegate
.
The first thing you should know is convert your UIImage
to NSData
and viceversa. You can use for this the following code:
If PNG images
let image = UIImage(named: "nameOfYourImage.jpg")
let data = UIImagePNGRepresentation(image)
If JPG images
let image = UIImage(named: "nameOfYourImage.jpg")
let data = UIImageJPEGRepresentation(image, 1.0)
Then you can use the WCSession
to send the message like in the following way:
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)
}
}
In the above code when you open the ViewController
it sends the UIImage
, the above example is only for learning purposes, you have to handle it in a more proper way regarding the complexity of your project.
I hope this help you.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…