WatchSyncService
此框架用于在 iOS 和 watchOS 之间方便地进行数据同步。它适用于两个平台,并可同时在两个平台上使用。
安装
pod 'WatchSyncService'
工作原理
默认行为
watch 应用未运行
iOS 应用未运行
示例
模型
enum State: Int {
case idle
case waiting
case failed
case succeeded
}
extension State: ISyncItem {
// should be unique across all item types
static var syncTypeId: ISyncItemType {
return "state"
}
// you should return property-list data types (numbers, string, data etc)
var syncValue: Any {
return self.rawValue
}
static func instatiate(with syncValue: Any) -> ISyncItem? {
if let rawValue = syncValue as? Int {
return State(rawValue: rawValue)
}
return State.idle
}
}
使用服务
// listen incoming messages (on both iOS and watchOS)
GenericSyncService.setSyncTipes(types: [State.self]) // On both iOS and watchOS apps
GenericSyncService.default.onReceived(type: State.self) { (state) in
print("state received: ", state.rawValue)
}
// send message (on both iOS and watchOS)
GenericSyncService.default.send(State.waiting)
灵活性
您可以 ISyncItem
使用任何类型:类、结构体、枚举。例如,数组
public class User: Codable {
var id = UUID()
var name = ""
var children = [User]()
init(name: String) {
self.name = name
}
}
extension Array: ISyncItem where Element == User {
public static var syncTypeId: ISyncItemType {
return "users"
}
public var syncValue: Any {
return try! JSONEncoder().encode(self)
}
public static func instatiate(with syncValue: Any) -> ISyncItem? {
if let data = syncValue as? Data {
return try? JSONDecoder().decode([User].self, from: data)
}
return nil
}
}
let child = User(name: "Ivan")
let father = User(name: "Alex")
father.children = [child]
GenericSyncService.setSyncTipes(types: [User.self])
GenericSyncService.default.onReceived(type: [User].self) { (users) in
print("received users")
}
GenericSyncService.default.send([father])