我检查用户是否登录到 iCloud,如果没有,我会设置警报。但是我想将用户发送到适当的设置,用户可以在其中实际登录到 iCloud,并且一旦登录就完全重定向到当前 View Controller 。
如何修改这段代码?
var iCloudStatus:Bool = false
func ifUserLoggedinToICloud() -> Bool {
let alertController = UIAlertController(title: "Alert", message: "iCloud Status", preferredStyle: .alert)
defaultContainer.accountStatus(completionHandler: { (accountStatus, error) in
if (accountStatus == .available) {
print("iCloud is available")
iCloudStatus = true
}
else {
print("iCloud is not available, log into iCloud")
alertController.message = "iCloud not available, log into iCloud"
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
})
return iCloudStatus
}
最佳答案
帐户状态检查是异步的,因此正如 Vadian 评论的那样,在更改 ifUserLoggedInToICloud
之前,该函数将始终返回 false。您应该在完成闭包中运行代码。
您可以通过以下方式将用户引导至设置:
defaultContainer.accountStatus(completionHandler: { (accountStatus, error) in
switch accountStatus {
case .noAccount, .restricted:
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else { return }
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
// Completion handler when settings opened
})
case .available:
print("Account available")
case .couldNotDerermine:
print("Error")
}
})
您不能将用户从设置页面重定向回来。是否导航回您的应用取决于用户。
有私有(private) API 可以重定向到特定的 iOS 设置页面(例如 "App-Prefs:root=CASTLE"
URL),但 Apple 不允许使用这些。
关于ios 检查用户是否登录到 icloud,如果没有则将用户发送到设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57649054/