Getting errors from Twitter.sharedInstance() Swift 3 iOS 10 - ios

I am writing app with Swift 3 on iOS 10. sharedInstance() method throws errors to console when user deny permissions to account from systems or account is not configured (e.g. "Unable to authenticate using the system account"). Errors are shows on console before enter to closure. I wont shows this errors to users in app e.g. on alert. This is my code:
Twitter.sharedInstance().logIn { (session, error) in
if error != nil {
// print(error?.localizedDescription ?? " ")
return
})
I get this error:
2016-11-29 14:49:09.023 CarReview[1254:31719] [TwitterKit] did encounter error with message "Unable to authenticate using the system account.": Error Domain=TWTRLogInErrorDomain Code=2 "User allowed permission to system accounts but there were none set up." UserInfo={NSLocalizedDescription=User allowed permission to system accounts but there were none set up.}
2016-11-29 14:49:09.024 CarReview[1254:31719] [TwitterKit] No matching scheme found.
2016-11-29 14:49:09.292 CarReview[1254:31719] [TwitterKit] did encounter error with message "Error obtaining user auth token.": Error Domain=TWTRLogInErrorDomain Code=-1 "<?xml version="1.0" encoding="UTF-8"?>
<hash>
<error>Desktop applications only support the oauth_callback value 'oob'</error>
<request>/oauth/request_token</request>
</hash>
" UserInfo={NSLocalizedDescription=<?xml version="1.0" encoding="UTF-8"?>
<hash>
<error>Desktop applications only support the oauth_callback value 'oob'</error>
<request>/oauth/request_token</request>
</hash>
}
I want show users this: "Unable to authenticate using the system account. User allowed permission to system accounts but there were none set up."

I am facing the same issue as in the question.
I have just set the callBack Url into the Twitter App and resolved the issues.
Go to https://apps.twitter.com/app -> Settings -> Callback URL and Update Settings to save.

I'm not sure I understand what you want to do but you probably want to print the result on the main thread:
Twitter.sharedInstance().logIn{(session, error) in
DispatchQueue.main.async{
if error != nil {
print("Failed to login with Twitter / error:", error!.localizedDescription)
}else{
print("succeeded")
}
}
}

OK, I use this code to notify user about some error:
if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeTwitter) {
if ACAccountStore().accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter).accessGranted {
Twitter.sharedInstance().logIn{
(session, error) in
if error != nil {
self.showAlert(title: "Twitter - Error", message: (error?.localizedDescription)!)
return
}
guard let token = session?.authToken else { return }
guard let secret = session?.authTokenSecret else { return }
let credential = FIRTwitterAuthProvider.credential(withToken: token, secret: secret)
FIRAuth.auth()?.signIn(with: credential, completion: { (user, error) in
if error != nil {
self.showAlert(title: "Firebase (Twitter)", message: (error?.localizedDescription)!)
return
}
self.showAlert(title: "Firebase (Twitter)", message: "Logged to Firebase via Twitter.")
})
}
} else {
showAlert(title: "Twitter - Error", message: "Give access to the system Twitter account.")
}
} else {
showAlert(title: "Twitter - Error", message: "No system accounts set up.")
}
But it isn't what I want:/

You need to use withMethods and specify using the systemAccounts, not webBased or all to use the iOS Twitter settings. The following code is in Swift 3:
twitSharedInstance.logIn(withMethods: .systemAccounts) { (session :TWTRSession?, error :Error?) in
if (error != nil) {
if (session != nil) {
//We have logged into Twitter.
}
}
}

Related

Firebase Email Verification Redirect Url

I incorporated Firebase's email verification for my iOS mobile app and am trying to resolve the following issues:
The length of the redirect url appears extremely long. It looks like it repeats itself.
https://app.page.link?link=https://app.firebaseapp.com//auth/action?apiKey%3XXX%26mode%3DverifyEmail%26oobCode%3XXX%26continueUrl%3Dhttps://www.app.com/?verifyemail%253Demail#gmail.com%26lang%3Den&ibi=com.app.app&ifl=https://app.firebaseapp.com//auth/action?apiKey%3XXX%26mode%3DverifyEmail%26oobCode%3XXX%26continueUrl%3Dhttps://www.app.com/?verifyemail%253Demail#gmail.com%26lang%3Den
When I set handleCodeInApp equal to true, and am redirected back to the app when I click on the redirect url, the user's email is not verified. Whereas when I set it to false and go through Firebase's provided web widget, it does get verified. Wasn't able to find documentation that outlined handling the former in swift...
Any thoughts are appreciated.
func sendActivationEmail(_ user: User) {
let actionCodeSettings = ActionCodeSettings.init()
let redirectUrl = String(format: "https://www.app.com/?verifyemail=%#", user.email!)
actionCodeSettings.handleCodeInApp = true
actionCodeSettings.url = URL(string: redirectUrl)
actionCodeSettings.setIOSBundleID("com.app.app")
Auth.auth().currentUser?.sendEmailVerification(with: actionCodeSettings) { error in
guard error == nil else {
AlertController.showAlert(self, title: "Send Error", message: error!.localizedDescription)
return
}
}
}
Make sure you're verifying the oobCode that is part of the callback URL.
Auth.auth().applyActionCode(oobCode!, completion: { (err) in
if err == nil {
// reload the current user
}
})
Once you have done that, try reloading the the user's profile from the server after verifying the email.
Auth.auth().currentUser?.reload(completion: {
(error) in
if(Auth.auth().currentUser?.isEmailVerified)! {
print("email verified")
} else {
print("email NOT verified")
}
})

LinkedIn login with custom token ( ERROR_INVALID_CUSTOM_TOKEN )

I am trying to login with LinkedIn using the native app and the LinkedIn SDK. So far I can login using the web if the LinkedIn app is not installed. I can also login with LinkedIn and get a token in return. But when I try to authenticate with Firebase I get this error:
Optional(Error Domain=FIRAuthErrorDomain Code=17000 "The custom token
format is incorrect. Please check the documentation." UserInfo=
{NSLocalizedDescription=The custom token format is incorrect. Please
check the documentation., error_name=ERROR_INVALID_CUSTOM_TOKEN})
This is my code:
// App installed
let permissions = [LISDK_BASIC_PROFILE_PERMISSION,LISDK_EMAILADDRESS_PERMISSION]
LISDKSessionManager.createSession(withAuth: permissions, state: nil, showGoToAppStoreDialog: true, successBlock: { (returnState) -> Void in
LISDKAPIHelper.sharedInstance().getRequest("https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,picture-url,public-profile-url,industry,positions,location)?format=json", success: { (response) -> Void in
if let data = response?.data.data(using: String.Encoding.utf8) {
if let dictResponse = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers){
let token = LISDKSessionManager.sharedInstance().session.accessToken.accessTokenValue
Auth.auth().signIn(withCustomToken: token! ) { (user, error) in
print(user!)
print(error!)
}
}
}
}, error: { (error) -> Void in
print("LINKEDIN error\(String(describing: error))")
})
}) { (error) -> Void in
print("error login linkedin")
}
The token I am sending to Firebase is a String, so that should be okay. I must be missing something. But what ?
The problem was my misunderstanding. I thought I could use the Linkedin token directly. It has to go to a webservice that uses the Firebase admin user to generate the token.

iOS Tweet compose issue

Previously i installed TwitterKit through Fabric. Now i have upgrade it to 3.0.1, Now i am facing problem with composing tweet.
This is my code:
let composer = TWTRComposer()
composer.setText("just setting up my Twitter Kit")
composer.setImage(UIImage(named: "twitterkit"))
// Called from a UIViewController
composer.show(from: self.navigationController!) { (result in
if (result == .done) {
print("Successfully composed Tweet")
} else {
print("Cancelled composing")
}
}
and i am getting following error:
[TwitterKit] did encounter error with message "Error obtaining user auth token.": Error Domain=TWTRLogInErrorDomain Code=-1 "
Desktop applications only support the oauth_callback value 'oob'
/oauth/request_token
" UserInfo={NSLocalizedDescription=
Desktop applications only support the oauth_callback value 'oob'
/oauth/request_token
}
I have already login in my twitter app in my device. When i checking with following condition it always return to else block.
if ([[Twitter sharedInstance].sessionStore hasLoggedInUsers]) {
} else {
}
My requirement is compose tweet from my app. if the user have twitter account in their device otherwise it will ask user to login .

Firebase unlink email/password auth from user on iOS

I'm trying to unlink email/password authentication from a user in Swift on iOS. I've read the documentation and managed to link and unlink Facebook authentication without a problem. However, after linking email/password credentials successfully, the providerData object is nil. The providerID is "Firebase" but when I pass that to the unlink code the following error is thrown:
Error Domain=FIRAuthErrorDomain Code=17016 "User was not linked to an account with the given provider." UserInfo={NSLocalizedDescription=User was not linked to an account with the given provider., error_name=ERROR_NO_SUCH_PROVIDER}
The unlink code I'm using is:
let providerId = (FIRAuth.auth()?.currentUser?.providerID)!
print("Trying to unlink:",providerId) // providerId = "Firebase"
FIRAuth.auth()?.currentUser?.unlinkFromProvider(providerId) { user, error in
if let error = error {
print("Unlink error:", error)
} else {
// Provider unlinked from account successfully
print("Unlinked...user.uid:", user!.uid, "Anonymous?:", user!.anonymous)
}
}
Reading the docs and having got it working for Facebook, I expected the providerData array to be populated with something after email authentication. So is my linking code wrong (it doesn't throw an error and appears to work fine)?
My linking code:
let credential = FIREmailPasswordAuthProvider.credentialWithEmail(email, password: password)
FIRAuth.auth()?.currentUser!.linkWithCredential(credential) { (user, error) in
if user != nil && error == nil {
// Success
self.success?(user: user!)
dispatch_async(dispatch_get_main_queue(), {
self.dismissViewControllerAnimated(true, completion: nil)
if type == "new" {
print("New user logged in...")
}
if type == "existing" {
print("Existing user logged in...")
}
})
} else {
print("Login error:",error)
self.showOKAlertWithTitle("Login Error", message: error!.localizedDescription)
}
}
Any pointers of how I can modify my approach would be great.
To get the profile information retrieved from the sign-in providers linked to a user, use the providerData property.
if let user = FIRAuth.auth()?.currentUser {
for profile in user.providerData {
// Id of the provider (ex: facebook.com)
let providerID = profile.providerID
}
} else {
// No user is signed in.
}
Calling FIRAuth.auth()?.currentUser?.providerID will result to "firebase".

ParseTwitterUtils Internal Server Error

I just finished up movie my app over to Parse Server. I've got everything working except for my Twitter Login and Signup. When I login or signup, I get an Internal Server Error message printed to my console. I am using the latest Parse SDK. Here is my login code (my signup code is similar, it just gets other data from the Twitter API and stores it to my database):
PFTwitterUtils.logInWithBlock {
(user: PFUser?, error: NSError?) -> Void in
if let user = user {
if user.isNew {
spinningActivity.hideAnimated(true)
PFUser.currentUser()?.deleteInBackground()
self.displayNoticeWithTwoActions("Account Not Found", message: "This Twitter account is not in our system. You have to sign up first.", firstButtonTitle: "Sign Up", closeButtonTitle: "Ok", segue: "dontHaveAccountSegue")
} else if error != nil {
spinningActivity.hideAnimated(true)
self.displayError("Error", message: error!.localizedDescription)
} else {
spinningActivity.hideAnimated(true)
self.performSegueWithIdentifier("successfulLoginSegue", sender: self)
}
} else {
spinningActivity.hideAnimated(true)
self.displayError("Error", message: "Unless you tapped on 'Cancel' or 'Done', something went wrong. Please try again.")
}
}
The only thing I could find online is that it could be a problem on Twitter's end...I made sure my consumer key and secret were right in my AppDelegate. Any ideas?
To your index.js file that is your config file for Parse Server, you'll need to add this:
var api = new ParseServer ({
databaseURI: xxxxxxx,
cloud: xxxxxx,
appID: xxxxxx,
//more keys
//add oauth keys
oauth: {
facebook: {
appIds: xxxxxxxxxxxxx
},
twitter: {
appIds: xxxxxxxxxxxxx
}
}
})

Resources