Facebook Login Error - Xcode 8 GM - facebook

I am using the latest Facebook SDK and I get this error when I run the block of code below: Facebook signup error - The operation couldn’t be completed. (com.facebook.sdk.login error 308.)
Here is my code:
func signupWithFacebook() {
FBSDKLoginManager().logIn(withReadPermissions: ["public_profile"], from: self) { (result, error) in
if let error = error {
print("Facebook signup error - \(error.localizedDescription)")
} else if result != nil {
let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
self.facebookSignup = true
self.addUserToAuth(credential, twitterUserID: "")
}
}
}

I Figured it out! It has to do with the way Apple deals with Keychain. All you have to do is go into the "Compatibilities" tab under the target for your app and turn "Keychain Sharing" on. Here is a more fulfilling answer.

Related

requestAccessToAccounts not performing in Xcode9

I have an app that uses a Twitter project to access tweets. It worked fine in Xcode 8 simulators but when I tried to run it on my device which is using iOS 11.2.1, I have problems. Also, using XCode9 simulators is causing the same issue. The app is not asking for permission to access Twitter with a popup like it was before. The following code handles the request:
func performTwitterSLRequest(_ request: SLRequest, handler: #escaping (PropertyList?) -> Void) {
if let account = twitterAccount {
request.account = account
request.perform { (jsonResponse, httpResponse, _) in
var propertyListResponse: PropertyList?
if jsonResponse != nil {
propertyListResponse = try? JSONSerialization.jsonObject(with: jsonResponse!, options: .mutableLeaves)
if propertyListResponse == nil {
let error = "Couldn't parse JSON response."
self.log(error)
propertyListResponse = error
}
} else {
let error = "No response from Twitter."
self.log(error)
propertyListResponse = error
}
self.synchronize {
self.captureFollowonRequestInfo(propertyListResponse)
}
handler(propertyListResponse)
}
} else {
let accountStore = ACAccountStore()
let twitterAccountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccounts(with: twitterAccountType, options: nil) { (granted, _) in
if granted {
if let account = accountStore.accounts(with: twitterAccountType)?.last as? ACAccount {
twitterAccount = account
self.performTwitterSLRequest(request, handler: handler)
} else {
let error = "Couldn't discover Twitter account type."
self.log(error)
handler(error)
}
} else {
let error = "Access to Twitter was not granted."
self.log(error)
handler(error)
}
}
}
}
I am just getting: "Access to Twitter was not granted." Has requestAccessToAccounts been deprecated or could there be another cause of the problem?
Indeed, support for accessing Twitter (or Facebook, etc) accounts using the ACAccount framework has been removed as of iOS 11.
Per the release notes for iOS 11 build 15a5278f:
Social accounts have been removed from Settings in iOS 11. Third-party apps will no longer have access to those signed-in accounts.
Twitter has posted a note on how to work around this using their TwitterKit framework. However, they've recently (April 2018) announced that they are discontinuing support for it. You may need to look for other (ie. open source) options for this, as it should be still possible using their API.

CKContainer.discoverAllIdentities always fails

The CKContainer.discoverAllIdentities request always fails in my CloudKit app. It has continually failed over the course of several days.
A simplified version of the code that is failing (which results in the same error) is:
private func getContacts(completion: (([CKUserIdentity]?) -> Void)?) {
container.status(forApplicationPermission: .userDiscoverability) { [weak self] status, error in
if let error = error {
print(error)
}
switch status {
case .granted:
self?.discover(completion: completion)
default:
print("status not granted")
}
}
}
private func discover(completion: (([CKUserIdentity]?) -> Void)?) {
let op = CKDiscoverAllUserIdentitiesOperation()
op.qualityOfService = .userInitiated
op.discoverAllUserIdentitiesCompletionBlock = { error in
if let error = error {
print(error)
}
}
op.userIdentityDiscoveredBlock = { identity in
print(identity)
}
op.start()
}
It results in an error being passed to the op.discoverAllUserIdentitiesCompletionBlock. The description of the error in the log is:
<CKError 0x1c4a51a60: "Server Rejected Request" (15/2000); server message = "Internal server error"; uuid = F67453B9-712D-4E5E-9335-929123E3C978; container ID = "iCloud.com.huntermaximillionmonk.topdraw">
Previously, this operation would work, but only for certain iCloud users. Now it's not for both of my test users.
Problem:
This was a problem in iOS 11.0
Based on my testing:
This works ok in Xcode 9.2 / iOS 11.2.1 on the device (not simulator)
After resetting the simulator works for the first time, doesn't work subsequently, however on the device it works repeatedly.
Code:
let queue = OperationQueue()
func requestPermissions(for permissions: CKApplicationPermissions,
completionHandler: #escaping (CKApplicationPermissionStatus, Error?) -> ()) {
CKContainer.default().requestApplicationPermission(permissions) { status, error in
if let error = error {
print("Error for requesting \(permissions) - \(error)")
}
let statusMessage : String
switch status {
case .granted:
statusMessage = "Granted"
case .denied:
statusMessage = "Denied"
case .couldNotComplete:
statusMessage = "Could not complete"
case .initialState:
statusMessage = "Initial state"
}
print("Permission - \(statusMessage)")
completionHandler(status, error)
}
}
private func discoverAllUsers() {
let operation = CKDiscoverAllUserIdentitiesOperation()
operation.userIdentityDiscoveredBlock = { userIdentity in
print("userIdentity = \(userIdentity)")
}
operation.discoverAllUserIdentitiesCompletionBlock = { error in
if let error = error {
print("Discover all users Error: \(error) ")
}
else {
print("Discover all users completed successfully")
}
}
queue.addOperation(operation)
}
Edit:
Apple fixed this issue day after this answer was posted, coincidence?! I don't think so :)
This is not actually the answer to the question, but a fix that helped me to cross over this error. It will require you to change your app UI interaction and add ContactsUI framework to your project, moreover your user will be responsible for selecting a contact with iCloud related email.
Good news is that the method discoverUserIdentity is still works. So, you can use it to get CKUserIdentity from manually selected contact.
func addContact(_ contact:CNContact) {
var lookUpEmails = [CKUserIdentityLookupInfo]()
for email in contact.emailAddresses {
lookUpEmails.append(CKUserIdentityLookupInfo(emailAddress: (email.value as String)))
}
let checkUserOperation = CKDiscoverUserIdentitiesOperation()
checkUserOperation.userIdentityLookupInfos = lookUpEmails
checkUserOperation.userIdentityDiscoveredBlock = { [unowned self] (identity, info) -> Void in
if identity.hasiCloudAccount {
if let recordID = identity.userRecordID {
//do something with discovered user
}
checkUserOperation.cancel()
}
}
checkUserOperation.queuePriority = Operation.QueuePriority.high
CKContainer.default().add(checkUserOperation)
}
It might sound useless, but in my case, it helped me to solve the Server Rejected Request" (15/2000) error, to fix one of the features of my app and continue to use the other feature related code with less efforts than I thought.
I hope someone will find this helpful.
Just another data point on this that might help with the overall picture. I was still seeing this error on 11.2.5 when I used my own iCloud AppleID (with hundreds of contacts) while running a Test App that called discoverAllIdentitiesWithCompletionHandler. I'd get the dreaded
CKError 0x1c0051730: "Server Rejected Request" (15/2000); server message = "Internal server error".
When I switched to run the exact same code on my daughters iOS11.2.5 device (with just a handful of contacts) the code worked fine.
Leads me to believe there is some rate limiting going on when there are a lot of contacts with iOS11.
(P.S. No errors at all running on iOS10)

Swift Firebase Facebook didCompleteWithResult error

I am currently trying to enable Facebook login with Firebase in my swift project. I have followed multiple tutorials, and created a Facebook app, and filled in the necessary info (app ID, valid OAuth redirect URI etc).
However, when I try to sign in - I get an error in the didCompleteWithResult function. To be more specific, on this line:
let credential = FIRFacebookAuthProvider.credential(withAccessToken: result.token.tokenString)
This is what the whole function looks like:
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
print("Works!")
if error != nil {
print("Error")
} else {
let credential = FIRFacebookAuthProvider.credential(withAccessToken: result.token.tokenString)
print("It worked.")
print(credential)
}
}
So as you can see on the code, according to the function - there is no error (according to the if else (error) statement). What could be the problem here?
Help is much appreciated!
Replace your credentials with this instead.
let facebookCredential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)

Implementing Github authentication with Firebase and Xcode (swift)

I've been receiving this error "An internal error has occurred, print and inspect the error details for more information" when trying to login through the access-token I receive from Github.
let credential = FIRGitHubAuthProvider.credentialWithToken(accessToken)
FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in
if let error = error {
print(error.localizedDescription)
}
}
It seems the issue is happening here but I'm not so sure why. Thank you in advance!

Firebase Storage Upload Error: FIRStorageErrorDomain Code=-13000

I am trying to upload an image to Firebase and I actually succeeded several times yesterday, but today I'm getting this error:
Optional
- Some : Error Domain=FIRStorageErrorDomain Code=-13000 "An unknown error occurred, please check the server response." UserInfo={ResponseErrorDomain=FIRStorageErrorDomain, object=ProfileImages/ascascasc ascas.jpg, error_name=ERROR_USER_NOT_FOUND, bucket=ichallenge-c52ae.appspot.com, ResponseErrorCode=-13020, NSLocalizedDescription=An unknown error occurred, please check the server response.}
I want to reiterate: nothing was changed in the code between yesterday and today, it just stopped working. This is the code, I've highlighted the line where it happens with a comment:
#IBAction func signUpButtonPressed(sender: AnyObject)
{
// If textfields have more than 3 characters
if firstNameTextField.text!.characters.count > 3 && passwordTextField.text!.characters.count > 3 && emailTextField.text!.containsString("#")
{
createUser()
//Goes to Main Storyboard
parseOutdated.signUpInBackgroundWithBlock { (success: Bool, error: NSError?) in
NSNotificationCenter.defaultCenter().postNotificationName("Login", object: nil)
}
}
else
{
firstNameShake.shakeAnimation()
lastNameShake.shakeAnimation()
passwordShake.shakeAnimation()
emailShake.shakeAnimation()
}
}
func createUser()
{
//Unwrap optionals before pushing to Firebase Database
let name: String = "\(self.firstNameTextField.text!) \(self.lastNameTextField.text!)"
storeProfileImage(name)
}
func storeProfileImage(name: String)
{
let profileImageData = UIImageJPEGRepresentation(self.profileImageView.image!, 1.0)
// Create a reference to the file you want to upload
let profileImageRef = storageRef.child("ProfileImages/\(name).jpg")
// Upload the file to the path defined above
profileImageRef.putData(profileImageData!, metadata: nil) { metadata, error in
if (error != nil) //ERROR HAPPENS HERE
{
print("Image not stored: ", error?.localizedDescription)
}
else
{
//Stores the profile image URL and sends it to the next function
let downloadURL = metadata!.downloadURL()
self.storeUserData(name, profileImageURL: downloadURL!)
}
}
}
Here's a screenshot of the breakpoint in XCode:
Any help provided would be deeply appreciated.
If you have been testing with the same user witout signing out on your app, your authentication token might have expired. Try signing out firs