ios 检查用户是否登录到 icloud,如果没有则将用户发送到设置

标签 ios swift xcode9.4

我检查用户是否登录到 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/

相关文章:

objective-c - 在 xcode 中,如何调用返回值的类方法?

ios - 自升级到 Xcode 6.1 以来,xcodebuild 命令无法为设备构建

swift - 在 Swift 中制作相同类型字典的空副本

ios - 如何在 UITableViewCell 中调用 popviewcontroller

ios - Swift:创建字典值数组

ios - 以编程方式触发 textFieldShouldClear

ios - 多个命令产生 ../Debug-iphonesimulator/RA_Swift copy.app/Info.plist' : 1)

ios - Swift:从 SQLite.swift 访问 NULL 值时应用程序崩溃

ios - 更新xcode后出现很多错误

lldb - 如何在 Xcode 控制台中删除 Hook 1 (expr -- @import UIKit display @import Appkit)