Check If User Is Logged into Icloud? Swift/Ios

Check if User is Logged into iCloud? Swift/iOS

Here you go - hopefully self explanatory. For more look at the Apple docs for the NSFileManager function below.

func isICloudContainerAvailable()->Bool {
if let currentToken = NSFileManager.defaultManager().ubiquityIdentityToken {
return true
}
else {
return false
}
}

See extract below:
An opaque token that represents the current user’s iCloud identity (read-only)
When iCloud is currently available, this property contains an opaque object representing the identity of the current user. If iCloud is unavailable for any reason or there is no logged-in user, the value of this property is nil.

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

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.

How to check if user is signed in into iCloud before saving data

You need to use accountStatusWithCompletionHandler from the CKContainer class and check the accountStatus returned.

This is described in the CloudKit Quick Start documentation.

Here is the Swift version of the example:

    CKContainer.defaultContainer().accountStatusWithCompletionHandler { accountStatus, error in
if accountStatus == .NoAccount {
let alert = UIAlertController(title: "Sign in to iCloud", message: "Sign in to your iCloud account to write records. On the Home screen, launch Settings, tap iCloud, and enter your Apple ID. Turn iCloud Drive on. If you don't have an iCloud account, tap Create a new Apple ID.", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
// Code if user has account here...
}
}


Related Topics



Leave a reply



Submit