简体   繁体   中英

ios check if user is logged into icloud and if not send user to settings

I check if user is logged into iCloud, if not I set a alert. But instead I want to send the user to appropriate settings, where user can actually log into iCloud and once logged in is complete redirect to current view controller.

How to I modify this code?

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
    }

The account status check is asynchronous, so as Vadian commented, the funtion will always return false before ifUserLoggedInToICloud is altered. You should run the code in the completion closure.

You can direct a user to settings with the following:

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

You cannot redirect the user back from the settings page. It is up to the user to navigate back to your app.

There are private APIs to redirect to specific iOS settings pages (such as the "App-Prefs:root=CASTLE" URL), but Apple do not permit use of these.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM