前言: 如果我们想存一些数据,并且换了一个设备登录,存储的数据还能查找到,就可以使用iCloud
在使用iCloud之前,需要判断当前设备的iCloud账号是否可用
import CloudKit class ViewController: UIViewController{ let container = CKContainer.default() override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(applicaitonBecameActive(notification:)), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicaitonWillResignActiveNotification(notification:)), name: UIApplication.willResignActiveNotification, object: nil) } @objc func applicaitonBecameActive(notification:NSNotification){ //当用户的iCloud账号发生变化时,调用该方法 NotificationCenter.default.addObserver(self, selector: #selector(handleIdentityChanged(notification:)), name: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: nil) } @objc func applicaitonWillResignActiveNotification(notification:NSNotification){ NotificationCenter.default.removeObserver(self, name: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: nil) } @objc func handleIdentityChanged(notification:NSNotification){ let fileManager = FileManager() if let token = fileManager.ubiquityIdentityToken{ print("new token:(token)") }else{ print("用户退出iCloud") } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) container.accountStatus {[weak self] (status, error) in if error != nil{ print("---------error:(error)") }else{ switch status{ case .couldNotDetermine: print("couldNotDetermine:获取账号出错") break case .available: print("available:可用") break case .restricted: print("restricted:受限制") break case .noAccount: print("noAccount:无账号") break default: print("default") } } } } deinit { NotificationCenter.default.removeObserver(self) } }