Switch iCloud configuration and use of the (a)

Introduction: If we want to save some data, and a device for a login, stored data can also find, you can use iCloud

 Before using iCloud, you need to determine the current device's iCloud account is available

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)
    }
}

 

Guess you like

Origin www.cnblogs.com/hualuoshuijia/p/12040028.html