mod*_*itt 9 ios swift watchkit swift2 watchos-2
我怎么能转移的UIImage过WatchConnecitivity从iPhone到苹果手表只加载在手机上无需用户交互,而且由于手表它调用编程.我需要这个,因为用于创建UIImageWatchkit API中不可用的使用逻辑的图像处理,所以它必须从手机创建.我似乎有一些使用Watch Connectivity的例子:
func startSession() {
session?.delegate = self
session?.activateSession()
}
Run Code Online (Sandbox Code Playgroud)
但是,我对手表套件和iOS一般都很陌生,对于如何使用这个会话管理器很困惑,特别是从手表到设备,而不是像我在网上的例子中看到的那样.有人可以提供一个如何在手表和手机上执行此操作的示例,以便UIImage从手表上拨打电话吗?
Vic*_*ler 12
要在iPhone和Apple Watch之间传输文件,您应使用Watch Connectivity,WCSession以便正确处理通信.您可以发送UIImage作为NSData使用didReceiveMessageData的委托方法WCSessionDelegate.
你应该知道的第一件事就是将你转变UIImage为NSData反之亦然.您可以使用以下代码:
如果PNG图像
let image = UIImage(named: "nameOfYourImage.jpg")
let data = UIImagePNGRepresentation(image)
Run Code Online (Sandbox Code Playgroud)
如果JPG图像
let image = UIImage(named: "nameOfYourImage.jpg")
let data = UIImageJPEGRepresentation(image, 1.0)
Run Code Online (Sandbox Code Playgroud)
然后您可以使用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.
}
}
Run Code Online (Sandbox Code Playgroud)
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)
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,当你打开ViewController它发送时UIImage,上面的例子仅用于学习目的,你必须以更合适的方式处理它,关于项目的复杂性.
我希望这对你有帮助.
| 归档时间: |
|
| 查看次数: |
4768 次 |
| 最近记录: |