栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用Watch Connectivity传输UIImage

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用Watch Connectivity传输UIImage

要在iPhone和Apple Watch之间传输文件,您应该使用Watch
Connectivity,

WCSession
以正确处理通信。您可以使用的委托方法发送
UIImage
as
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
,上面的示例仅出于学习目的,您必须以更适当的方式处理项目的复杂性。

希望对您有所帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/616397.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号