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.
If you just want to know if the user is logged in to iCloud, the synchronous method can be used:
if FileManager.default.ubiquityIdentityToken != nil {
print("iCloud Available")
} else {
print("iCloud Unavailable")
}
If the ubiquityIdentityToken
is nil
and you'd like to know why iCloud isn't available, you can use the asynchronous method:
CKContainer.default().accountStatus { (accountStatus, error) in
switch accountStatus {
case .available:
print("iCloud Available")
case .noAccount:
print("No iCloud account")
case .restricted:
print("iCloud restricted")
case .couldNotDetermine:
print("Unable to determine iCloud status")
}
}
Note that this requires the use of CloudKit, which requires the CloudKit entitlement:
<key>com.apple.developer.icloud-services</key>
<array>
<string>CloudKit</string>
</array>
If you want to use the asynchronous method but don't care about why, you should check that accountStatus
is available
, rather than checking that it is not noAccount
:
CKContainer.default().accountStatus { (accountStatus, error) in
if case .available = accountStatus {
print("iCloud Available")
} else {
print("iCloud Unavailable")
}
}