Check if User is Logged into iCloud? Swift/iOS

99封情书 提交于 2019-11-30 11:22:47

问题


Is there a way for me to check and see if a user is logged into iCloud when they open the app up? I want to be able to direct them to the settings page if they are not logged in, and if they are logged into iCloud and have used the app before - I want to skip the sign in page....

I looked into Apple's iCloud and Cloudkits documentation but was unable to find anything that would be of assistance! Is this even possible to do?


回答1:


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.




回答2:


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

However, if 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")
    }
}

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



回答3:


I think this async method is preferred so that you don't block while you are checking.

        CKContainer.defaultContainer().accountStatusWithCompletionHandler { (accountStat, error) in
          if (accountStat == .Available) {
              print("iCloud is available")
          }
          else {
              print("iCloud is not available")
          }
        }


来源:https://stackoverflow.com/questions/32335942/check-if-user-is-logged-into-icloud-swift-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!