How To Authenticate Files On Iphone

by -26 views

You tin let your users authenticate with Firebase using their Google Accounts by integrating Google Sign-In into your app.

Before yous begin

  1. Add Firebase to your Apple projection. Include the post-obit pods in your
    Podfile:

    pod 'FirebaseAuth' pod 'GoogleSignIn'
              
  2. If you haven’t yet connected your app to your Firebase project, do so from the Firebase console.
  3. Enable Google as a sign-in method in the Firebase panel:
    1. In the Firebase console, open the
      Auth
      department.
    2. On the
      Sign in method
      tab, enable the
      Google
      sign-in method and click
      Relieve.

First, y’all must import the Firebase SDK and Google Sign-In SDK header files into your app.

Swift

import FirebaseCore import GoogleSignIn
          

Objective-C

@import FirebaseCore; @import GoogleSignIn;
          

2. Implement Google Sign-In

Implement Google Sign-In by following these steps. Run across the Google Sign-In developer documentation for details on using Google Sign-In with iOS.

  1. Add custom URL schemes to your Xcode projection:
    1. Open your project configuration: double-click the project proper noun in the left tree view. Select your app from the
      TARGETS
      department, then select the
      Info
      tab, and aggrandize the
      URL Types
      section.
    2. Click the
      +
      push, and add a URL scheme for your reversed client ID. To find this value, open the


      GoogleService-Info.plist


      configuration file, and wait for the
      REVERSED_CLIENT_ID
      central. Copy the value of that fundamental, and paste information technology into the
      URL Schemes
      box on the configuration page. Leave the other fields blank.

      When completed, your config should look something similar to the post-obit (just with your application-specific values):

  2. In your app delegate’s
    awarding:didFinishLaunchingWithOptions:
    method, configure the
    FirebaseApp
    object.

    Swift

    // Use Firebase library to configure APIs FirebaseApp.configure()
                  

    Objective-C

    // Use Firebase library to configure APIs [FIRApp configure];
                  
  3. Implement the
    application:openURL:options:
    method of your app delegate. The method should call the
    handleURL
    method of the
    GIDSignIn
    instance, which will properly handle the URL that your application receives at the end of the authentication process.

    Swift

    @available(iOS 9.0, *) func application(_ application: UIApplication, open url: URL,                  options: [UIApplication.OpenURLOptionsKey: Any])   -> Bool {   render GIDSignIn.sharedInstance.handle(url) }
                  

    Objective-C

    - (BOOL)application:(nonnull UIApplication *)application             openURL:(nonnull NSURL *)url             options:(nonnull NSDictionary<NSString *, id> *)options {   return [[GIDSignIn sharedInstance] handleURL:url]; }
                  
  4. Pass the presenting view controller and client ID for your app to the Google Sign In sign-in method and create a Firebase auth credential from the resulting Google auth token:

    Swift

    guard let clientID = FirebaseApp.app()?.options.clientID else { render }  // Create Google Sign In configuration object. let config = GIDConfiguration(clientID: clientID)  // Start the sign in flow! GIDSignIn.sharedInstance.signIn(with: config, presenting: self) { [unowned self] user, mistake in    if let fault = error {     // ...     render   }    guard     let authentication = user?.authentication,     let idToken = authentication.idToken   else {     return   }    allow credential = GoogleAuthProvider.credential(withIDToken: idToken,                                                  accessToken: authentication.accessToken)    // ... }
                  

    Objective-C

    GIDConfiguration *config = [[GIDConfiguration alloc] initWithClientID:[FIRApp defaultApp].options.clientID];  __weak __auto_type weakSelf = cocky; [GIDSignIn.sharedInstance signInWithConfiguration:config presentingViewController:self callback:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {   __auto_type strongSelf = weakSelf;   if (strongSelf == nil) { return; }    if (error == nil) {     GIDAuthentication *authentication = user.authentication;     FIRAuthCredential *credential =     [FIRGoogleAuthProvider credentialWithIDToken:hallmark.idToken                                      accessToken:authentication.accessToken];     // ...   } else {     // ...   } }];
                  
  5. Add a
    GIDSignInButton
    to your storyboard, XIB file, or instantiate it programmatically. To add the push button to your storyboard or XIB file, add a View and ready its custom class to
    GIDSignInButton.
  6. Optional: If you desire to customize the button, do the following:

    Swift

    1. In your view controller, declare the sign-in push equally a property.
      @IBOutlet weak var signInButton: GIDSignInButton!
    2. Connect the button to the
      signInButton
      belongings you just declared.
    3. Customize the button by setting the properties of the GIDSignInButton object.

    Objective-C

    1. In your view controller’s header file, declare the sign-in button every bit a property.
      @belongings(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;
    2. Connect the push to the
      signInButton
      property you just declared.
    3. Customize the button by setting the properties of the GIDSignInButton object.

3. Authenticate with Firebase

Finally, complete the Firebase login procedure with the auth credential created in the previous step.

Swift

Auth.auth().signIn(with: credential) { authResult, error in     if let error = error {       let authError = mistake every bit NSError       if isMFAEnabled, authError.lawmaking == AuthErrorCode.secondFactorRequired.rawValue {         // The user is a multi-factor user. 2d gene challenge is required.         allow resolver = authError           .userInfo[AuthErrorUserInfoMultiFactorResolverKey] equally! MultiFactorResolver         var displayNameString = ""         for tmpFactorInfo in resolver.hints {           displayNameString += tmpFactorInfo.displayName ?? ""           displayNameString += " "         }         self.showTextInputPrompt(           withMessage: "Select cistron to sign in\due north\(displayNameString)",           completionBlock: { userPressedOK, displayName in             var selectedHint: PhoneMultiFactorInfo?             for tmpFactorInfo in resolver.hints {               if displayName == tmpFactorInfo.displayName {                 selectedHint = tmpFactorInfo as? PhoneMultiFactorInfo               }             }             PhoneAuthProvider.provider()               .verifyPhoneNumber(with: selectedHint!, uiDelegate: nil,                                  multiFactorSession: resolver                                    .session) { verificationID, error in                 if error != cipher {                   impress(                     "Multi factor start sign in failed. Error: \(error.debugDescription)"                   )                 } else {                   self.showTextInputPrompt(                     withMessage: "Verification code for \(selectedHint?.displayName ?? "")",                     completionBlock: { userPressedOK, verificationCode in                       let credential: PhoneAuthCredential? = PhoneAuthProvider.provider()                         .credential(withVerificationID: verificationID!,                                     verificationCode: verificationCode!)                       permit assertion: MultiFactorAssertion? = PhoneMultiFactorGenerator                         .assertion(with: credential!)                       resolver.resolveSignIn(with: exclamation!) { authResult, mistake in                         if error != zip {                           print(                             "Multi factor finanlize sign in failed. Error: \(error.debugDescription)"                           )                         } else {                           self.navigationController?.popViewController(animated: true)                         }                       }                     }                   )                 }               }           }         )       } else {         self.showMessagePrompt(fault.localizedDescription)         return       }       // ...       return     }     // User is signed in     // ... }

Objective-C

[[FIRAuth auth] signInWithCredential:credential                           completion:^(FIRAuthDataResult * _Nullable authResult,                                        NSError * _Nullable error) {     if (isMFAEnabled && mistake && fault.code == FIRAuthErrorCodeSecondFactorRequired) {       FIRMultiFactorResolver *resolver = error.userInfo[FIRAuthErrorUserInfoMultiFactorResolverKey];       NSMutableString *displayNameString = [NSMutableString string];       for (FIRMultiFactorInfo *tmpFactorInfo in resolver.hints) {         [displayNameString appendString:tmpFactorInfo.displayName];         [displayNameString appendString:@" "];       }       [cocky showTextInputPromptWithMessage:[NSString stringWithFormat:@"Select factor to sign in\n%@", displayNameString]                            completionBlock:^(BOOL userPressedOK, NSString *_Nullable displayName) {        FIRPhoneMultiFactorInfo* selectedHint;        for (FIRMultiFactorInfo *tmpFactorInfo in resolver.hints) {          if ([displayName isEqualToString:tmpFactorInfo.displayName]) {            selectedHint = (FIRPhoneMultiFactorInfo *)tmpFactorInfo;          }        }        [FIRPhoneAuthProvider.provider         verifyPhoneNumberWithMultiFactorInfo:selectedHint         UIDelegate:nil         multiFactorSession:resolver.session         completion:^(NSString * _Nullable verificationID, NSError * _Nullable mistake) {           if (error) {             [cocky showMessagePrompt:fault.localizedDescription];           } else {             [self showTextInputPromptWithMessage:[NSString stringWithFormat:@"Verification code for %@", selectedHint.displayName]                                  completionBlock:^(BOOL userPressedOK, NSString *_Nullable verificationCode) {              FIRPhoneAuthCredential *credential =                  [[FIRPhoneAuthProvider provider] credentialWithVerificationID:verificationID                                                               verificationCode:verificationCode];              FIRMultiFactorAssertion *assertion = [FIRPhoneMultiFactorGenerator assertionWithCredential:credential];              [resolver resolveSignInWithAssertion:assertion completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {                if (fault) {                  [self showMessagePrompt:error.localizedDescription];                } else {                  NSLog(@"Multi factor finanlize sign in succeeded.");                }              }];            }];           }         }];      }];     }   else if (mistake) {     // ...     return;   }   // User successfully signed in. Become user data from the FIRUser object   if (authResult == null) { render; }   FIRUser *user = authResult.user;   // ... }];

Next steps

After a user signs in for the first time, a new user account is created and linked to the credentials—that is, the user name and countersign, phone number, or auth provider information—the user signed in with. This new business relationship is stored as part of your Firebase project, and tin be used to identify a user across every app in your project, regardless of how the user signs in.

  • In your apps, you tin become the user’south basic profile data from the
    FIRUser
    object. Encounter Manage Users.

  • In your Firebase Realtime Database and Cloud Storage Security Rules, you lot can get the signed-in user’southward unique user ID from the
    auth
    variable, and use it to control what information a user can access.

You can allow users to sign in to your app using multiple authentication providers past linking auth provider credentials to an existing user account.

To sign out a user, call
signOut:.

Swift

            let firebaseAuth = Auth.auth() do {   effort firebaseAuth.signOut() } catch let signOutError as NSError {   print("Error signing out: %@", signOutError) }
          

Objective-C

            NSError *signOutError; BOOL condition = [[FIRAuth auth] signOut:&signOutError]; if (!status) {   NSLog(@"Fault signing out: %@", signOutError);   return; }
          

Yous may also want to add fault treatment code for the full range of authentication errors. See Handle Errors.

Source: https://firebase.google.com/docs/auth/ios/google-signin