iOS Revisited: Firebase

Hot

Post Top Ad

Showing posts with label Firebase. Show all posts
Showing posts with label Firebase. Show all posts

10 Dec 2019

Firebase Dynamic Link Not Found in swift ios

12/10/2019 04:50:00 am 0
Failed to resolve uri domain prefix: https://www.yourdomain.com.

If you are the developer of this app, ensure that your Dynamic Links domain is correctly configured and that the path component of this URL is valid.

If you are the developer of this app, ensure that your Dynamic Links domain is correctly configured and that the path component of this URL is valid.

Possible reasons for the invalid dynamic link error:

Reason 1:

First thing you need to check with apple-app-site-association as follow

paste your domain with apple-app-site-association https://www.yourdomain.com/apple-app-site-association.

Expected output should be

{"applinks":{"apps":[],"details":[{"appID":"LQABBB9F84.com.yourdomain.YourDomain","paths":["NOT /_/*","/*"]}]}}

Incase if you are getting `Dynamic Link Not Found` means check the following two things:

1. App Store ID is valid or not
2. Team ID should be same the one in provising profile

Reason 2:

Second possbile reason might be in capabilities.

Enable assocaited domains and add your domain as applinks:www.yourdomain.com.

Here make sure that you need to remove https://, otherwise deeplink url will not work as expected.

Reason 3:

If you are using any custom domains that means you are not using domains that ends with page.link, you need to add FirebaseDynamicLinksCustomDomains key in info.plist.

<key>FirebaseDynamicLinksCustomDomains</key>
<array>
    <string>https://www.yourdomain.com/test1</string>
    <string>https://www.yourdomain.com/test2</string>
</array>


Not required if you are using domains with page.link.

Reason 4:

On some iOS devices it always goes to browser, but the same link will work on other ios devices. This is because of safari caching.

Go to settings in iOS device, then tap on safari and open reader, then tap on edit select preview.page.link and delete.

Go to settings in iOS device, then tap on safari and open reader, then tap on edit select preview.page.link and delete.

That's it should work fine.

Tip: You can try pasting the url in notes app and long press on the link then tap on `open in your app'

Read More

8 Oct 2017

Storing/Downloading/Deleting images or videos Using Firebase Cloud Storage

10/08/2017 10:07:00 am 9
Cloud Storage for Firebase is a powerful, simple, and cost-effective object storage service built for Google scale. Firebase SDK adds Google security to file uploads and downloads for your Firebase apps, either if connectivity is slow or fast.

Storing/Downloading images or videos Using Firebase Cloud Storage


If the network connection is poor, the client is able to retry the operation right where it left off, saving your users time and bandwidth. Everything will be done asynchronously in background threads, so that UI won't hang.

We can store images, videos, files, audio in cloud storage by using Firebase SDK. For accessing those files we can use same Google cloud storage.

Uploads and downloads are robust, meaning they restart where they stopped, saving your users time and bandwidth.

Google provides strong security, so that only authenticated users can upload or download files.

Before getting in to Sample Project, Integrate your project with Firebase.

Add the following dependency to podfile:
pod 'Firebase/Storage'

Run pod install and open the created .xcworkspace file.

Configure Firebase Storage Rules:

The Firebase Storage provides a set rules so that files can structure according to the rules.

By default, only authenticated users can access to the Firebase Storage for uploading & downloading files.

There are different authenticated methods choose any one of them.

Using Facebook Login
Using Email & Password
Anonymous Login

In this project we are going to start without setting up Authentication, you can configure your rules for public access.

Go to Firebase console -> Storage -> Rules

Add the following rule and publish:
// Anyone can read or write to the bucket, even non-users of your app.
// Because it is shared with Google App Engine, this will also make
// files uploaded via GAE public.
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}


 Firebase console -> Storage -> Rules


Set up Firebase Storage To iOS Project :

We need to initialize Firebase.

First import the Firebase SDK in AppDelegate.swift file:
import Firebase

Then, in the application:didFinishLaunchingWithOptions: method, initialize the FirebaseApp object:
// Use Firebase library to configure APIs
FirebaseApp.configure()

Open ViewController.swift file add the following code inside viewDidLoad() method:
let storage = Storage.storage()

Create a Reference To upload, download, or delete:

References are created using the FirebaseStorage service and calling its reference method.
// Create a storage reference from our storage service
let storageRef = storage.reference()

You can create a reference to a location lower in the tree, say 'images/car.jpg', by using the child method on an existing reference.
var carRef = storageRef.child("images/car.jpg")

Uploading To Cloud Storage :

For uploading a file firstly we need a reference, we can use the one which created earlier.

We can upload files to storage using two ways:

1. Upload from data in memory
2. Upload from a URL representing a file on device

Here we will show using memory.

Before doing that drag one image to the project and name its as 'car.jpg'.

Add the following method and call in viewDidLoad() method:
func uploadImageToStorage() {
    let storage = Storage.storage()
    var storageRef = storage.reference()
    
    if let image = UIImage(named: "car.jpg") {
        let data = UIImagePNGRepresentation(image)
        print("data \(String(describing: data))")
        
        
        // Create the file metadata
        let metadata = StorageMetadata()
        metadata.contentType = "image/jpeg"
        
        storageRef = storageRef.child("images/car.jpg")
        
        let uploadTask = storageRef.putData(data!, metadata: metadata)
        
        // Listen for state changes, errors, and completion of the upload.
        uploadTask.observe(.resume) { snapshot in
            // Upload resumed, also fires when the upload starts
        }
        
        uploadTask.observe(.pause) { snapshot in
            // Upload paused
        }
        
        uploadTask.observe(.progress) { snapshot in
            // Upload reported progress
            let percentComplete = 100.0 * Double(snapshot.progress!.completedUnitCount)
                / Double(snapshot.progress!.totalUnitCount)
            
            print("Upload Percentage == \(percentComplete)")
        }
        
        uploadTask.observe(.success) { snapshot in
            // Upload completed successfully
            print("Upload completed successfully")
        }
        
        uploadTask.observe(.failure) { snapshot in
            if let error = snapshot.error as? NSError {
                switch (StorageErrorCode(rawValue: error.code)!) {
                case .objectNotFound:
                    // File doesn't exist
                    break
                case .unauthorized:
                    // User doesn't have permission to access file
                    break
                case .cancelled:
                    // User canceled the upload
                    break
                    
                    /* ... */
                    
                case .unknown:
                    // Unknown error occurred, inspect the server response
                    break
                default:
                    // A separate error occurred. This is a good place to retry the upload.
                    break
                }
            }
        }
    }
}

Above method will give percentage of upload done,failures causes, pause, resume and success observer.

Build and Run,if everything is correct then we will see 'Upload completed successfully' message in the console.

Then open Firebase console check inside storage -> images -> car.jpg should be there like below:

 storage -> images -> car.jpg


Downloading Image From Cloud Storage:

Now we will download the car image what we uploaded before.

Add the following code and call in viewDidLoad() method:
func downloadImageFromStorage() {
    let storage = Storage.storage()
    var storageRef = storage.reference()
    
    // Create a reference to the file we want to download
    storageRef = storageRef.child("images/car.jpg")
    
    // Start the download (in this case writing to a file)
    let downloadTask = storageRef.getData(maxSize: 5 * 1024 * 1024) { data, error in
        if let error = error {
            // Uh-oh, an error occurred!
        } else {
            // Data for "images/island.jpg" is returned
            let image = UIImage(data: data!)
            
            print("image succesfully downloaded \(image!)")
        }
    }
    
    
    // Observe changes in status
    downloadTask.observe(.resume) { snapshot in
        // Download resumed, also fires when the download starts
    }
    
    downloadTask.observe(.pause) { snapshot in
        // Download paused
    }
    
    downloadTask.observe(.progress) { snapshot in
        // Download reported progress
        let percentComplete = 100.0 * Double(snapshot.progress!.completedUnitCount)
            / Double(snapshot.progress!.totalUnitCount)
    }
    
    downloadTask.observe(.success) { snapshot in
        // Download completed successfully
    }
    
    // Errors only occur in the "Failure" case
    downloadTask.observe(.failure) { snapshot in
        guard let errorCode = (snapshot.error as? NSError)?.code else {
            return
        }
        guard let error = StorageErrorCode(rawValue: errorCode) else {
            return
        }
        switch (error) {
        case .objectNotFound:
            // File doesn't exist
            break
        case .unauthorized:
            // User doesn't have permission to access file
            break
        case .cancelled:
            // User cancelled the download
            break
            
            /* ... */
            
        case .unknown:
            // Unknown error occurred, inspect the server response
            break
        default:
            // Another error occurred. This is a good place to retry the download.
            break
        }
    }
}

Above method will give percentage of download done,failures causes, pause, resume and success observer.

Build and Run,if everything is correct then we will see 'image successfully downloaded with file' message in the console.


Deleting Image From Firebase Storage:

We will delete the car image from Firebase storage.

Add the following code and call in viewDidLoad() method:
func deletingImageFromStorage(){
    let storage = Storage.storage()
    var storageRef = storage.reference()
    
    // Create a reference to the file we want to download
    storageRef = storageRef.child("images/car.jpg")
    
    storageRef.delete { error in
        if let error = error {
            // Uh-oh, an error occurred!
        } else {
            print("File deleted successfully")
        }
    }
    
}

Build and Run,if everything is correct then we will see 'File deleted successfully' message in the console.

Open the Firebase console and check whether image deleted or not.

Read More

5 Oct 2017

Firebase Cloud Firestore Example Project in iOS - Swift

10/05/2017 06:43:00 am 1
Cloud Firestore is a scalable database like Firebase Realtime Database, it keeps your data in sync across client apps through real time listeners and offers offline support for mobile and web so you can build responsive apps that work regardless of network latency or Internet connectivity.

The advantage of using Cloud Firestore is Expressive querying. You can use queries to retrieve individual, specific documents or to retrieve all the documents in a collection that match your query parameters. Your queries can include multiple, chained filters and combine filtering and sorting.

Data Structure:

Cloud Storage data structure will be like following image:

Firebase Cloud Firestore Data Structure
Here we store data in Documents. Documents are like Dictionaries a key value pair which support many different data types, from simple strings and numbers, to complex, nested objects.

Firebase Cloud Firestore Documents

These documents are stored in collections, which are containers for your documents that you can use to organize your data and build queries.

Firebase Cloud Firestore Collection of Documents
Querying in Cloud Firestore is expressive, efficient, and flexible. We can do query to retrieve data at the document level without needing to retrieve the entire collection, or any nested subcollections.

We can do pagination by adding sorting, filtering, and limits to queries. Adding realtime listeners to your app notifies you with a data snapshot whenever the data your client apps are listening to changes, retrieving only the new changes.

Getting Started:

First create sample project in Xcode and add one UILabel, two UITextField's and one UIButton and give outlets. Build and Run that should look like as below:

Sample Demo

Next open Firebase Console -> Database -> Cloud Firestore, next pop up will come with two options, select start in test mode then enable.

Set up Firebase Cloud Firestore To iOS Project :

Next getting into Sample Project,First Integrate your project with Firebase.

Add the following dependencies to podfile:
pod 'Firebase/Core'
pod 'Firebase/Firestore'

Save the file, Run 'pod install' and open the created .xcworkspace file.

Next, We need to initialize Firebase.

Open Xcode project.

First import the Firebase SDK in AppDelegate.swift file:
import Firebase

Then, in the application:didFinishLaunchingWithOptions: method, initialize the FirebaseApp object:
// Use Firebase library to configure APIs
FirebaseApp.configure()

Saving/Adding data to Cloud Firestore:

Open ViewController.swift, add the docRef property.
var docRef : DocumentReference!

Add the following code in viewDidLoad() method:
docRef = Firestore.firestore().document("friends/profile")

By the way, here we are storing friends name and his/her profession. Above reference is the path where we are going to store our data as a Document.

Next add the code for saving data. Add the following code in save button action method:
@IBAction func saveButtonTapped(_ sender: UIButton) {
    guard let name = nameField.text, !name.isEmpty else { return }
    guard let profession = professionField.text, !profession.isEmpty else { return }
    
    let dataToSave : [String: Any] = ["name": name, "profession": profession]
    docRef.setData(dataToSave) { (error) in
        if let error = error {
            print("Oh no! Some error \(error.localizedDescription)")
        }else {
            print("Data has been saved")
        }
    }
}

Run and enter the data in text fields, then tap save button. We will see message as 'Data has been saved'.

Next open Firebase console -> Database -> Cloud Storage:

Firebase console -> Database -> Cloud Storage:

Fetching/Getting data From Cloud Firestore:


Fetching is very simple, we need to get the data from same docRef.

Before that add fetch button to the view and give action outlet.

Adding Button

Add the following code inside fetch button action method:
@IBAction func fetchButtonTapped(_ sender: Any) {
    docRef.getDocument { (docSnapshot, error) in
        guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }
        let data = docSnapshot.data()
        let name = data["name"] as? String ?? ""
        let profession = data["profession"] as? String ?? ""
        self.titleLabel.text = "\(name) is a \(profession)"
    }
}

Run and tap Fetch button, we will see the data at the top like follow:

Fetching/Getting data From Cloud Firestore:

 

Listening for RealTime in Cloud Firestore:

First add the following listener property.
var dataListener : FIRListenerRegistration!

Next add the viewWillAppear() method as following:
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    dataListener =  docRef.addSnapshotListener { (docSnapshot, error) in
        guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }
        let data = docSnapshot.data()
        let name = data["name"] as? String ?? ""
        let profession = data["profession"] as? String ?? ""
        self.titleLabel.text = "\(name) is a \(profession)"
    }
}

Above listener will keep on calling every time the data changes. So we need to remove the observer on viewWillDisappear. So that we can avoid memory problems.

Add the following method:
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    dataListener.remove()
}

Run the project, we can see the title without tapping fetch button. That's good.

Next step is update data in real time. Now add some text in text field then tap save button.

On saving only we can see the title changes in real time without fetch action.

Listening for RealTime in Cloud Firestore:


Conclusion:

Cloud Firestore offers robust access management,Expressive querying and authentication. Secure data by using authentication and rules.


Download sample project with examples :

Read More

1 Oct 2017

Firebase RealTime Database Example Project in iOS - Swift 4

10/01/2017 01:40:00 am 0
Data is stored as JSON and synchronized in realtime to every connected client devices. The Firebase RealTime Database is a cloud-hosted database.

Firebase RealTime Database Example Project in iOS - Swift 4

Data is persisted locally, and even while offline, realtime events continue to fire, giving the end user a responsive experience.

Here we need to structure data, so that inserting and fetching will be done easily. Because the Firebase RealTime Database allows nesting data up to 32 levels deep, you might be tempted to think that this should be the default structure.

Best practices for data structure

Before getting in to Sample Project, Integrate your project with Firebase.

Add the following dependency to podfile:
pod 'Firebase/Database'

Run pod install and open the created .xcworkspace file.

Configure Firebase Database Rules:

The RealTime Database provides a set rules so that data can structure according to the rules.

By default, only authenticated users can access to the RealTime Database for performing read and write operations.

There are different authenticated methods choose any one of them.

Authenticate with Firebase using Facebook Login

Firebase Authentication using Email & Password

Authenticate with Firebase Anonymously on iOS

In this project we are going to start without setting up Authentication, you can configure your rules for public access.

Go to Firebase console -> Database -> Rules

Add the following rule and publish:
// These rules give anyone, even people who are not users of your app,
// read and write access to your database
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Go to Firebase console -> Database -> Rules

Set up Firebase Realtime Database :

We need to initialize Firebase.

First import the Firebase SDK in AppDelegate.swift file:
import Firebase

Then, in the application:didFinishLaunchingWithOptions: method, initialize the FirebaseApp object:
// Use Firebase library to configure APIs
FirebaseApp.configure()

Once you've initialized Firebase Realtime Database, define and create a reference to your database as follows:

Open ViewController.swift file add the following code inside viewDidLoad() method:
var ref: DatabaseReference!

ref = Database.database().reference()

Writing Data:

Here we can show basic write operations.

Pass types that correspond to the available JSON types as follows:
  •     NSString
  •     NSNumber
  •     NSDictionary
  •     NSArray
For instance, we can add a username by using 'setValue' as follow:
ref.child("users").setValue(["username": "Jhon"])

Build and Run, It runs successfully. Open Firebase console we can see the users dictionary with username as John.

Open Firebase console we can see the users dictionary

Reading Data By Listening :

The FIRDataEventTypeValue event is fired every time data is changed at the specified database reference, including changes to children. To limit the size of your snapshots, attach only at the highest level needed for watching changes. For example, attaching a listener to the root of your database is not recommended.

Add the following method and call in ViewDidLoad() method:
func readData() {
    let userRef = Database.database().reference().child("users")
    let refHandle : DatabaseHandle!
    refHandle = userRef.observe(.value, with: { (snapshot) in
        let userDict = snapshot.value as? [String : AnyObject] ?? [:]
        print(userDict)
        // ...
    })
}

Build and Run, we see an output in Xcode console.

Next for testing realtime go to firebase console and change the name from 'Jhon' to 'Snow'. We can see the log in Xcode console without sending any new request.

For removing the observer add the following code.
if let handle = refHandle {
    Database.database().reference().removeObserver(withHandle: handle)
}

SingleEvent Observer:

let userID = Auth.auth().currentUser?.uid
ref.child("users").observeSingleEvent(of: .value, with: { (snapshot) in
  // Get user value
  let value = snapshot.value as? NSDictionary
  let username = value?["username"] as? String ?? ""
  let user = User.init(username: username)

  // ...
  }) { (error) in
    print(error.localizedDescription)
}

The above observer will call only one time. Here no need to remove observer, it will be removed automatically after single request.

Read More

29 Sept 2017

Authenticate with Firebase Anonymously on iOS | Convert Anonymous User to Permanent User in iOS - swift 4

9/29/2017 01:40:00 am 0
We can create and use temporary anonymous accounts to authenticate with Firebase using Firebase Authentication. By using this we can allow users without signed up to your app to work with data protected by security rules. If later these anonymous user wants to sign up you can convert and link their sign-in credentials to the anonymous account so that they can continue to work with their protected data in future sessions.

Authenticate with Firebase Anonymously on iOS | Convert Anonymous User to Permanent User in iOS - swift 4

This Article Covers Following Related questions  :

Swift iOS Anonymous Sign-In
firebase authentication ios swift
firebase email authentication ios
firebase authentication ios tutorial
firebase authentication example ios
firebase user authentication tutorial
firebase anonymous login iOS
email login firebase ios

Before get into this, there are some steps to be done:

  • Enable Facebook Login:
    • In the Firebase console, open the Auth section.
    • On the Sign-in Methods page, enable the Anonymous sign-in method.


Sign In to Firebase anonymously:

If an user uses an app feature that requires authentication with Firebase, sign in the user anonymously by completing the following steps:

First import the Firebase SDK in AppDelegate.swift file:
import Firebase

Then, in the application:didFinishLaunchingWithOptions: method, initialize the FirebaseApp object:
// Use Firebase library to configure APIs
FirebaseApp.configure()

Call signInAnonymouslyWithCompletion: method:
Auth.auth().signInAnonymously() { (user, error) in
  // ...
  if let error = error {
        // ...
        print(error.localizedDescription)
        return
    }
    // User is signed in
    if let user = user {
        let uid = user.uid
        let isAnonymous = user!.isAnonymous  // true
        // ...
    }
}

If the above method executes without an error, you can get the anonymous user's account data from the FIRUser object:

Convert an anonymous/guest account to a permanent account:

If an anonymous user wants to sign up to your app, to continue in app for further work we can use the following steps.

Example: you might want to make the items the user added to their shopping cart before they signed up available in their new account's shopping cart.


When the user signs up, complete the sign-in flow for the user's authentication provider up to, but not including, calling one of the FIRAuth.signInWith methods. For example, get the user's Google ID token, Facebook access token, or email address and password.

Get an FIRAuthCredential for the new authentication provider:

Link anonymous with Google Sign-In:

For converting anonymous user to permanent user using Google Sign-In, To do so, complete the following :
guard let authentication = user.authentication else { return }
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                  accessToken: authentication.accessToken) 

user.link(with: credential) { (user, error) in
  if let error = error {
        // ...
        print(error.localizedDescription)
        return
    }
    // User is signed in with google
    if let user = user {
        // The user's ID, unique to the Firebase project.
        // Do NOT use this value to authenticate with your backend server,
        // if you have one. Use getTokenWithCompletion:completion: instead.
        let uid = user.uid
        let email = user.email
        let photoURL = user.photoURL
        // ...
    }
}

Link anonymous with Facebook Login:

For converting anonymous user to permanent user using Facebook Login, To do so, complete the following :
let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)

user.link(with: credential) { (user, error) in
  if let error = error {
        // ...
        print(error.localizedDescription)
        return
    }
    // User is signed in with Facebook
    if let user = user {
        // The user's ID, unique to the Firebase project.
        // Do NOT use this value to authenticate with your backend server,
        // if you have one. Use getTokenWithCompletion:completion: instead.
        let uid = user.uid
        let email = user.email
        let photoURL = user.photoURL
        // ...
    }
}

Link anonymous with Email-password sign-in:

For converting anonymous user to permanent user using Email-password sign-in, To do so, complete the following :
let credential = EmailAuthProvider.credential(withEmail: email, password: password)

user.link(with: credential) { (user, error) in
  if let error = error {
        // ...
        print(error.localizedDescription)
        return
    }
    // User is signed in with Email-password
    if let user = user {
        // The user's ID, unique to the Firebase project.
        // Do NOT use this value to authenticate with your backend server,
        // if you have one. Use getTokenWithCompletion:completion: instead.
        let uid = user.uid
        let email = user.email
        let photoURL = user.photoURL
        // ...
    }
}

If the call to linkWithCredential:completion: succeeds, the user's new account can access the anonymous account's Firebase data.

Sign Out:

In order to sign out a user from Firebase write the following code:
let firebaseAuth = Auth.auth()
do {
    try firebaseAuth.signOut()
} catch let signOutError as NSError {
    print ("Error signing out: %@", signOutError)
}

It will sign Out a user from Firebase and no longer access to Firebase.

Next Steps:

Authenticate with Firebase using Facebook Login


Firebase Authentication using Email & Password

Read More

27 Sept 2017

Authenticate with Firebase using Facebook Login on iOS - Swift 4

9/27/2017 02:52:00 am 0
We can authenticate users with Firebase with their Facebook accounts by integrating Facebook Login.

Authenticate with Firebase using Facebook Login on iOS - Swift 4

This Article Covers Following Related questions  :

Using Firebase to Integrate Facebook Login in iOS Apps
Firebase Facebook Login and Authentication Tutorial
Firebase Authentication using facebook login in iOS
Add Facebook authentication to your apps, using Firebase
iOS App using facebook login with firebase auth
Firebase - Facebook Authentication


Before get into this, there are some steps to be done:

  • Enable Facebook Login:
    • In the Firebase console, open the Auth section.
    • On the Sign in method tab, enable the Facebook sign-in method and specify the App ID and App Secret you got from Facebook.
    • Then, make sure your OAuth redirect URI (e.g. demo-app-12345.firebaseapp.com/__/auth/handler) is listed as one of your OAuth redirect URIs in your Facebook app's settings page on the Facebook for Developers site in the Product Settings > Facebook Login config.

Enable Facebook Login in firebase console

Facebook Integration:

Firstly we need to integrate Facebook to Xcode project before Authenticate with Firebase.

Integrate Facebook Login into your app by following the developer's documentation.

Next initialize the FBSDKLoginButton object, and set delegate to receive login and logout events. For example:
let loginButton = FBSDKLoginButton()
loginButton.delegate = self

Implement delegate method didCompleteWithResult:error:
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError?) {
  if let error = error {
    print(error.localizedDescription)
    return
  }
  // ... Successfully Logged in
}

Sign In To Firebase:

We need to initialize Firebase for Authentication.

First import the Firebase SDK in AppDelegate.swift file:
import Firebase

Then, in the application:didFinishLaunchingWithOptions: method, initialize the FirebaseApp object:
// Use Firebase library to configure APIs
FirebaseApp.configure()

After a user successfully signs in into Facebook the didCompleteWithResult:error:  method will call, there we get an access token for the signed-in user and exchange it for a Firebase credential:
let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)

Finally, authenticate with Firebase using the Firebase credential:
Auth.auth().signIn(with: credential) { (user, error) in
    if let error = error {
        // ...
        print(error.localizedDescription)
        return
    }
    // User is signed in
    if let user = user {
        // The user's ID, unique to the Firebase project.
        // Do NOT use this value to authenticate with your backend server,
        // if you have one. Use getTokenWithCompletion:completion: instead.
        let uid = user.uid
        let email = user.email
        let photoURL = user.photoURL
        // ...
    }
}

This new account is stored as part of your Firebase project, and can be used to identify a user across every app in your project, regardless of how the user signs in.

Sign Out:

In order to sign out a user from Firebase write the following code:
let firebaseAuth = Auth.auth()
do {
    try firebaseAuth.signOut()
} catch let signOutError as NSError {
    print ("Error signing out: %@", signOutError)
}

It will sign Out a user from Firebase and no longer access to Firebase.

Next Steps:


Firebase Authentication using Email & Password

 

Authenticate with Firebase Anonymously on iOS

 

Read More

26 Sept 2017

Firebase Authentication using Email & Password - iOS, Swift

9/26/2017 03:10:00 am 0
Now a days most of mobile developers are using Firebase in their projects.

For getting the data from Firebase we need to get authorization from Firebase. This can be done by Sign Up/Log In into Firebase.

Firebase Authentication using Email & Password

There are different Sign Up/Log In providers.

In this article we will go through Sign Up/Log In using Email & Password.

Before getting into Firebase Authentication, First we need to setup Firebase to our project.

If not, read setting up Firebase.

Next step is add the following pod file to our project.
pod 'Firebase/Auth'

Then, run pod install and open the created .xcworkspace file.

Initialize the Firebase SDK :

We need to initialize Firebase for Authentication.

First import the Firebase SDK in AppDelegate.swift file:
import Firebase

Then, in the application:didFinishLaunchingWithOptions: method, initialize the FirebaseApp object:
// Use Firebase library to configure APIs
FirebaseApp.configure()

Next go to Firebase console -> Authentication -> Sign-in Method there enable required logins.Here we enable Email/Password sign In provider.

 Firebase console -> Authentication -> Sign-in Method


Sign Up:

We need to collect user email and password for Firebase Authentication.

For creating new user, use the following method:
Auth.auth().createUser(withEmail: "test@email.com", password: "password") { (user, error) in
    if let error = error {
        print(error.localizedDescription)
        return
    }
    
    print("\(user!.email!) created")
}

After successful sign up we are printing user email from user object.

Sign In:

For signing in with email and password use the following code:
Auth.auth().signIn(withEmail: "test@email.com", password: "password") { (user, error) in
    if let error = error {
        print(error.localizedDescription)
        return
    }
    
    if let user = user {
        // The user's ID, unique to the Firebase project.
        // Do NOT use this value to authenticate with your backend server,
        // if you have one. Use getTokenWithCompletion:completion: instead.
        let uid = user.uid
        let email = user.email
        let photoURL = user.photoURL
        // ...
    }
}

After a user signs in successfully, you can get information about the user.

Sign Out:

In order to sign out from Firebase write the following code:
let firebaseAuth = Auth.auth()
do {
    try firebaseAuth.signOut()
} catch let signOutError as NSError {
    print ("Error signing out: %@", signOutError)
}

It will sign Out from Firebase and we can't access to Firebase.

Next Steps:

Authenticate with Firebase using Facebook Login

 

Authenticate with Firebase Anonymously on iOS

Read More

25 Sept 2017

could not find a valid GoogleService-Info.plist in your project - iOS, Swift, Objective-C

9/25/2017 11:38:00 pm 0

*** Terminating app due to uncaught exception 'com.firebase.core', reason: '`[FIRApp configure];` (`FirebaseApp.configure()` in Swift) could not find a valid GoogleService-Info.plist in your project. Please download one from https://console.firebase.google.com/.'
***

Solution 1:

Check the downloaded plist file name. The correct name should be 'GoogleService-Info.plist'.

Some names like GoogleService-Info(3).plist, GoogleService-Info(5).plist are invalid.

Firebase App configuration looks for the 'GoogleService-Info.plist' file. If the name is invalid and the app will crash with the above error.

So change name and Run, it should works without any error.

Solution 2:

Even though changing the name app still crashing then check the selected target for 'GoogleService-Info.plist'

For that first select 'GoogleService-Info.plist' file.

GoogleService-Info.plist'

Next in the right side panel of Xcode, select 'file inspector'. There we can see 'Target Membership' check our target.



Now try Build and Run,it should works without any error.
Read More

Firebase Tutorial - 1. Setting Up Google Firebase For iOS Projects

9/25/2017 03:53:00 am 0

Prerequisites :

  • Xcode
    • 7.0 or later for Objective-C
    • 8.0 or later for Swift 
  • Project targeting iOS 7 or above
  • Swift projects must use Swift 3.0 or later
  • CocoaPods 1.0.0 or later

Firebase :

Firebase helps you build better mobile apps and grow your business.

 Add &Integrate Firebase with iOS Project

Firebase products like Analytics, Real time Database, Messaging, and Crash Reporting let you move quickly and focus on your users.

Firebase is built on Google infrastructure and scales automatically, for even the largest apps.

Firebase products work great individually but share data and insights, so they work even better together.

In this tutorial we are going to know how to setup Firebase for mobile apps.

Getting Started :

Firstly we should have one gmail account for setting Up Firebase.

Go to https://firebase.google.com/.
Then tap on Sign In button at the top right corner of the page.

https://firebase.google.com/.

Enter your login credentials then tap sign in.

After successful login Firebase will show 'Welcome to Firebase' Screen with a Demo Project.

One more button is there 'IMPORT GOOGLE PROJECT'. If you have an existing project we can simply import from here.

But here we don't have any project to import.

Creating Project :

Create by tapping on Add Project button. It shows pop up like follow:

 Add Firebase Project Popup

Enter project name as 'Firebase-Demo'. then tap create project. It will go to inside project and looks like follow:


Left side we can see Authentication, Database, Storage, Hosting etc..

Firebase supports all those features with out our extra input. That's really cool.

In order to use all these features, firstly we need to create Xcode Project and then adding Firebase to the created Project.

Create Xcode Project :

Open Xcode -> File -> New -> Project -> Single View App, then tap next button. Type product name as 'Firebase-Demo' then tap next and select the folder to save project.

Cool that's it, next step is adding Firebase to our project.

Adding Firebase To iOS Project :

Go the Firebase  there we can see 'Add Firebase to your iOS app'.

'Add Firebase to your iOS app'.

Tap on that it will show a pop up. Here we need to add 'iOS bundle ID'. This id we will get from Xcode project.

Adding Firebase To iOS Project  pop up

Copy Bundle Id and Paste in the Firebase page. Then App Nickname & Store Id are optional. Then tap on 'Register App' button. Next it shows as following :


Next step download the the plist file as shown in above picture.

Drag the downloaded plist file to our Xcode project. And name it as 'GoogleService-Info.plist'.

Then tap to continue. It will go to next step for adding 'Firebase SDK' to our project using CocoaPods instructions.

CocoaPods Official Tutorial

adding 'Firebase SDK' to our project using CocoaPods instructions.

Close Xcode project then open terminal and go to the project directory by using commands.

Then enter the following command in terminal
pod init

Next add the following command in terminal
open -a Xcode Podfile

It open podfile there some code already exists. Add the following code after '# Pods for Firebase-Demo' line.
pod 'Firebase/Core'

Then save and run the following command.
pod install

It installs all the required pods to our projects as following:

Firebase pods intsllling in terminal

Next close Xcode and open 'Firebase-Demo.xcworkspace' file.

To connect Firebase when your app starts up, add the initialization code below to your main AppDelegate class.
import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(_ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)
    -> Bool {
    FirebaseApp.configure()
    return true
  }
}

Open Firebase we will see like following:

Firebase iOS Project Looks like

That's it we finished setting up the Firebase.

Now we can integrate storage, Database etc..

Next Steps:

Authenticate with Firebase using Facebook Login


Firebase Authentication using Email & Password

 

Authenticate with Firebase Anonymously on iOS

Read More

Post Top Ad