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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...