- 判断iCloud是否可用
func isIcloudAvailable() -> Bool{ if FileManager.default.ubiquityIdentityToken != nil{ return true } else { return false } }
- 获取默认的NSUbiquitousKeyValueStore
let kvoStore = NSUbiquitousKeyValueStore.default
- 设置数据
// NSUbiquitousKeyValueStore的使用方式和NSUserDefaults类似,可以存贮字符串,布尔值,整数,浮点数等 kvoStore.set("liu", forKey: "name") kvoStore.set(26, forKey: "age") kvoStore.synchronize()//// 同步数据,避免冲突
- 获取数据
kvoStore.string(forKey: "name") kvoStore.object(forKey: "age")
- 监听值的变化
NotificationCenter.default.addObserver(self, selector: #selector(dataChanged(noti:)), name: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: nil) @objc func dataChanged(noti:Notification){ print(noti.userInfo) } //千万不能忘记了在这里移除通知 deinit { NotificationCenter.default.removeObserver(self) }
判断云文件夹是否存在
let fileManager = FileManager() var documentDirectory:String? //判断文件是否存在 func doesDocumentDirectoryExist()->Bool{ var isDirectory = false as ObjCBool if let directory = documentDirectory{ if fileManager.fileExists(atPath: directory, isDirectory: &isDirectory){ if isDirectory.boolValue{ return true } } } return false } func createDocumentDirectory(){ if let directory = documentDirectory{ do{ try fileManager.createDirectory(at: NSURL.init(fileURLWithPath: directory) as URL, withIntermediateDirectories: true, attributes: nil) }catch{ } } } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let containerUrl = fileManager.url(forUbiquityContainerIdentifier: nil) documentDirectory = containerUrl!.path + "\Documents" if doesDocumentDirectoryExist() { print("已经存在了") }else{ createDocumentDirectory() } return true }