方法一:使用WatchConnectivity框架实现共享,适用于Watch OS2.0
新版本一种实现方式:Watch OS2.0之后使用WatchConnectivity框架的WCSessionDelegate代理实现传递文件:
1.引入WatchConnectivity
import WatchConnectivity
2.遵循协议WCSessionDelegate
3.定义并初始化session对象
var session: WCSession!
session = WCSession.default()
session.delegate = self
// 激活session 必须激活才能实现数据传递、消息传递
session.activate()
4.触发发送方法
let pathURL = Bundle.main.url(forResource: "share", withExtension: ".png")
// 发送
session.transferFile(pathURL!, metadata: ["keys":"allValues"])
5.实现代理方法
// iPhone必须实现的方法:
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?)
{}
func sessionDidBecomeInactive(_ session: WCSession)
{}
func sessionDidDeactivate(_ session: WCSession)
{}
6.watch中使用同样的方式,在代理中除了
// 必须实现的方法外
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?)
{}
// 使用下面的方法来获取并使用
func session(_ session: WCSession, didReceive file: WCSessionFile)
{}
方法二:使用App Groups , 适用于Watch OS1.0
1.创建证书




★这里Choose File选择的是从钥匙串中选择钥匙串访问-->从正式颁发机构请求证书-->存储到磁盘的文件


★选中后上传


★Continue之后会生成一个cer文件,点download下载到本地,然后在钥匙串打开就可以看到名称是刚才请求下来的证书文件了

★然后创建AppID


★App Services中勾选上必要的Service,此处勾选上AppGroups

★可以看到App Groups是待配置,待会到App Groups中配置即可





★创建完成,找到刚才创建的App ID,点Edit,在AppGroups点Edit,勾选上刚刚创建的Groups,Continue--> Assign-->Done,可以看到该App ID下的App Groups服务已被激活





★然后是创建配置文件,选中刚才的App ID,Continue,选择相关证书-->Continue-->勾选上适配的设备,Continue,填写信息后Continue,然后DownLoad








★打开该文件,在已创建的工程中Bulid Setting的CodeSinging勾选好开发证书,然后在TARGETS的Capabilities中打开App Groups,确保Steps里的三个对勾无报错后勾选之前创建的App Groups,继续以此方式设置watch的App Groups。

★★★★ 所幸,新版的Xcode已将上面繁琐的步骤化简,我们仅需要在创建工程时设置好BundleID,然后在TARGETS的General中的Singing项选好开发团队、勾选上Automatically manage signing,后续的一系列会自动创建~~~设置App Groups时,点加号后在group.后面填写相对应的APP ID就可以了


★watch的设置其WatchKit Extension即可


★注意:勾选完App Groups之后生成的一个配置文件里的App GroupsID是第一个

★代码获取:
首先给iPhone的工程中添加一张测试图片
1.在iPhone的文件中将该图放入到共享文件夹中
let fileManager = FileManager.default
//共享文件夹路径
let groupPath = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.zhangheng.DataSharingToWatch")?.path
shareLabel.text = groupPath
//找到图片
let imagePath = Bundle.main.path(forResource: "share.png",ofType: nil)??""
let imageData = NSData(contentsOfFile: imagePath)
//图片转存到共享文件夹的路径
let imageFullPath = groupPath?.appending("/share.png")
//存
fileManager.createFile(atPath: imageFullPath!,contents: imageData as?Data,attributes: nil)
2.在watch上读取
//路径group.com.zhangheng.DataSharingToWatch
let fileManager = FileManager.default
// group路径
let groupPath = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.zhangheng.DataSharingToWatch")?.path
var paths = groupPath??"watch读的路径没有"
print(paths)
//拿到图片
let imagePath = groupPath?.appending("/share.png")
let imageData = NSData(contentsOfFile: imagePath!)
if nil == imageData {
paths = imagePath! + "||没找到图|||".appending(paths)
}
pathLabel.setText(paths)
//装载
shareImageView.setImageData(imageData as Data?)
网友评论