Swift如何检测iCloud已登录(在线)
不少童鞋在使用iCloud同步的功能时会发现,你的App无法正常工作,尤其是在模拟器上运行App的时候!这是因为你模拟器上设置里的iCloud没有登录! 当你登录iCloud账号后,你会发现App神奇般的恢复正常了!一般的你可以在Xcode打开对应账号下的iCloud中存放的内容: 项目->Capabilities->iCloud->CloudKit Dashboard 按钮 地址如下: https://icloud.developer.apple.com/dashboard/ 不过还有一个问题需要解决,如何提前检测iCloud账户是否登录呢!? 这分两种情况:当使用iCloud里的Key-value storage功能时,官方文档称无法直接判断出iCloud账号是否已登录,原话如下: Key-value storage is effectively always available. If a
device is not attached to an account,changes created on
the device are pushed to iCloud as soon as the device is
attached to the account.
网上那些说使用NSUbiquitousKeyValueStore.default().synchronize()之类的方法都无效,它都返回true! 如果是使用iCloud中的iCloud Documents功能,在打开Capabilities中iCloud对应的选项后官方的原话是: Call the URLForUbiquityContainerIdentifier: method for one of your ubiquity containers. If the method returns nil,document storage is not available.
可以使用如下代码检测: func iCloudAccessTest(_ block:@escaping (Bool)->()){ DispatchQueue.global(qos: .default).async { if let _ = FileManager.default.url(forUbiquityContainerIdentifier: nil){ DispatchQueue.main.async { block(true) } }else{ DispatchQueue.main.async { block(false) } } } }
其实对于第一种情况(Key-value storage),也可以使用这个技巧,前提是必须打开iCloud中对应的选项即可. 而在使用CloudKit的情况下,可以如下方式判断: The public database is always available. The private
database is available only when the value in the
ubiquityIdentityToken property is not nil.
官方文档链接: iCloud Design Guide (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |