How can I get started with Quickblox API and Swift? - ios

I am trying to develop a very simple chat application using quickblox and swift.
Knowing that there are few tutorials online that try to explain the process, I started with creating a user in the application dashboard and getting its credentials to initiate the connection. (I am certain that the user credential are correct and the dashboard is correctly set as I have followed this tutorial)
Here is the Application view controller:
import UIKit
import Quickblox
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let user = QBUUser()
user.id = 29777469
user.password = "tahrisqalli"
QBChat.instance().connect(with: user) { (error) in
if error != nil {
print("error: \(error)")
}
else {
print("login to chat succeeded")
}
}
}
}
and following is the error I get telling me that I did not connect successfully.
2017-07-11 11:33:50.837 QuickbloxTutorial[1045:24701] [ChatService] Connecting to Chat, host: chat.quickblox.com, user JID: 29777469-0#chat.quickblox.com/DCB0A1F4-3A56-49AD-9639-8C2A6BBE7B08
2017-07-11 11:33:52.042 QuickbloxTutorial[1045:24711] [ChatService] Stream isSecure: YES
2017-07-11 11:33:52.658 QuickbloxTutorial[1045:24722] [ChatService] Stream did connect, supportsStartTLS: YES
2017-07-11 11:33:52.824 QuickbloxTutorial[1045:24722] [ChatService] Did not authenticate, error: <failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><not-authorized/></failure>
error: Optional(Error Domain=com.quickblox.chat Code=401 "<failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><not-authorized/></failure>" UserInfo={NSLocalizedDescription=<failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><not-authorized/></failure>})
2017-07-11 11:33:52.842 QuickbloxTutorial[1045:24722] [ChatService] Did disconnect

First of all, you have to log in with a user.
After this, You can connect with chat and it is best for you to use ServicesManager class that manage session automatically.
let loginUser = QBUUser()
loginUser.id = 29777469
loginUser.password = "tahrisqalli"
ServicesManager.instance().authService.logInWithUser(loginUser, completion: { (response, qbUser) in
if qbUser != nil {
ServicesManager.instance().chatService.connectWithCompletionBlock { (error) in
if error != nil {
print("user not connected error: ",error?.description)
} else {
//user connect successfully
}
}
print(qbUser)
} else {
print(response.error?.description)
}
})

Related

How to run a function after setupIntentConfirmation succeeds?

I can successfully create and confirm a setupIntent. After the user enters his credit card details and presses the "confirm" button, his payment method is successfully attached to their stripe customer account. However, when the setupIntent is confirmed, I'd like to run a function on my client to send the user to a different screen.
This is where I check the completion of the setupIntentConfirmation. The print statement shows in the console but for some reason, my function is not running.
func onCompletion(status: STPPaymentHandlerActionStatus, si: STPSetupIntent?, error: NSError?) {
self.setupIntentStatus = status
self.error = error
if status == .succeeded {
print("succeeded")
setIsVerifiedToTrue()
}
}
Here is the function I am trying to run:
func setIsVerifiedToTrue() {
let ref = FirebaseReferenceManager.root.collection(FirebaseKeys.CollectionPath.requirements).document(Auth.auth().currentUser!.uid)
ref.updateData([FirebaseKeys.RequirementsFieldPath.verified : true]) { error in
if let error = error {
print("Error updating document: \(error)")
} else {
print("isVerified set to true")
}
}
}
any help would be very much appreciated! :)

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".

Unable to get Facebook permissions after HTTPMethod DELETE in Swift

I am working on an app that logs in to Facebook using the FBSDK in Swift. I also have been able to make requests to get my wall posts by using
var request: FBSDKGraphRequest
request = FBSDKGraphRequest(graphPath: "me/feed"), parameters: ["access_token": FBSDKAccessToken.currentAccessToken().tokenString], HTTPMethod:"GET")
request.startWithCompletionHandler({(connection, result, error) -> Void in
if error != nil
{
}
else
{
}
})
but I have been unable to get back results after I used the following to log out
var deletePermission = FBSDKGraphRequest(graphPath: "me/permissions/", parameters: nil, HTTPMethod: "DELETE")
deleterPermission.startWithCompletionHandler({(connection, result, error) -> Void in
if error != nil
{
}
else
{
}
})
When I log back in to the app, I am again asked to accept permissions, but when I check the expiration date for the current token with FBSDKAccessToken.currentAccessToken().expirationDate I get a date before I tried HTTPMethod: DELETE.
So I was wondering how it would be possible to get back permission for your app or renew my access token because I don't think it's working by logging back in and accepting permissions. I have used the following to log out of the app
// Log out of the database I'm using
try! FIRAuth.auth()!.signOut()
// Log out of Facebook, clear current token and logged user
FBSDKAccessToken.setCurrentAccessToken(nil)
FBSDKProfile.setCurrentProfile(nil)
I am also using `FBSDKLoginButton()' and setting the following permissions to log in
var loginButton = FBSDKLoginButton()
loginButton.readPermissions = ["public_profile", "user_friends", "user_about_me", "user_posts"]
loginButton.delegate = self
....
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
if error == nil
{
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)
// Firebase authentication
FIRAuth.auth()?.signInWithCredential(credential) {(user, error) in
if error == nil
{
// No error found get user credentials through Firebase
}
else
{
}
}}
But again after logging in and going to another ViewController by segue and I check the current token to get "me/feed" I am not getting a reply and the token's expiration date has expired. Would it be easier to create a new app in Facebook developer and set it up in Xcode or is there something I can do to get my user posts?

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

Messenger cannot connect to a XMPP server from the first attempt

I wrote 2 functions:
if let stream = xmppStream {
if stream.isAuthenticated(){
println("Logged In")
} else {
println("something is wrong")
}
}
func xmppStreamDidConnect(sender: XMPPStream) {
println("xmppStreamDidConnect")
isOpen = true
var error: NSError?
if (xmppStream!.authenticateWithPassword(password.text, error: &error) ) {
println("authentification successful")
performSegueWithIdentifier("goToBuddyList", sender: nil)
}
}
And when I run my app it prints in the terminal:
something is wrong
xmppStreamDidConnect
authentification successful
Even if I putted true credentials it prints at first [something is wrong] and just later [authentification successful]. Why it happens?
I want alert users just in case of [something is wrong], not in [successful] case, but it alert it in successful case, too.
Implement xmppStreamDidAuthenticate and didNotAuthenticate methods of XMPPStreamDelegate .
After calling authenticateWithPassword client authentication will surely end up in above two function (xmppStreamDidAuthenticate and didNotAuthenticate) until then stream.isAuthenticated() will return “0”.

Resources