티스토리 뷰

macOS, iOS

[iOS] Facebook 로그인 - SwiftUI

SweetDev 2021. 5. 28. 11:16

1. pod 설치하기

pod 'FBSDKLoginKit'

 

2.

 

3. 

 func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    if let url = URLContexts.first?.url {
      // 카카오 간편로그인
      if AuthApi.isKakaoTalkLoginUrl(url) {
        _ = AuthController.handleOpenUrl(url: url)
      } else {
        // 네이버 간편로그인
        NaverThirdPartyLoginConnection
          .getSharedInstance()?
          .receiveAccessToken(URLContexts.first?.url)
      }
      // 페이스북
      ApplicationDelegate.shared.application(
          UIApplication.shared,
          open: url,
          sourceApplication: nil,
          annotation: [UIApplication.OpenURLOptionsKey.annotation]
      )
    }
  }

 

3. 뷰 만들기

// Swift
//
// Add this to the header of your file, e.g. in ViewController.swift 

import FBSDKLoginKit

// Add this to the body
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
	
        let loginButton = FBLoginButton()
        loginButton.center = view.center
        view.addSubview(loginButton)
    }
}

!! 근데 이걸로 만들면 facebook의 button으로 만들어진다. 나는 이미 디자이너가 만들어준 facebook 버튼이 따로 있어서 이걸로 어떻게 처리하는지 찾기 시작했다. 

 

@IBAction func loginButtonTapped(_ sender: Any) {
    
    // 1
    let loginManager = LoginManager()
    
    if let _ = AccessToken.current {
        // Access token available -- user already logged in
        // Perform log out
        
        // 2
        loginManager.logOut()
        updateButton(isLoggedIn: false)
        updateMessage(with: nil)
        
    } else {
        // Access token not available -- user already logged out
        // Perform log in
        
        // 3
        loginManager.logIn(permissions: [], from: self) { [weak self] (result, error) in
            
            // 4
            // Check for error
            guard error == nil else {
                // Error occurred
                print(error!.localizedDescription)
                return
            }
            
            // 5
            // Check for cancel
            guard let result = result, !result.isCancelled else {
                print("User cancelled login")
                return
            }
          
            // Successfully logged in
            // 6
            self?.updateButton(isLoggedIn: true)
            
            // 7
            Profile.loadCurrentProfile { (profile, error) in
                self?.updateMessage(with: Profile.current?.name)
            }
        }
    }
}

이거는 SwiftUI 아닐때

 

 

struct ContentView: View {
    @ObservedObject var fbmanager = UserLoginManager()
    var body: some View {
        Button(action: {
            self.fbmanager.facebookLogin()
        }) {
            Text("Continue with Facebook")
        }
    }
}

class UserLoginManager: ObservableObject {
    let loginManager = LoginManager()
    func facebookLogin() {
        loginManager.logIn(permissions: [.publicProfile, .email], viewController: nil) { loginResult in
            switch loginResult {
            case .failed(let error):
                print(error)
            case .cancelled:
                print("User cancelled login.")
            case .success(let grantedPermissions, let declinedPermissions, let accessToken):
                print("Logged in! \(grantedPermissions) \(declinedPermissions) \(accessToken)")
                GraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name"]).start(completionHandler: { (connection, result, error) -> Void in
                    if (error == nil){
                        let fbDetails = result as! NSDictionary
                        print(fbDetails)
                    }
                })
            }
        }
    }
}

이거는 SwiftUI에서

 

 

4. 이미 한번 로그인 한 사람은 두번 다시 연동하지 않아도 되게 처리한다. 

 

The FBSDKLoginManager sets this token for you and when it sets currentAccessToken it also automatically writes it to a keychain cache. 

The FBSDKAccessToken contains userID which you can use to identify the user. 

You should update your view controller to check for an existing token at load. This avoids unnecessary showing the login flow again if someone already granted permissions to your app:

 

// Swift

override func viewDidLoad() {
    super.viewDidLoad()

    if let token = AccessToken.current,
        !token.isExpired {
        // User is logged in, do work such as go to next view controller.
    }
}
    
// Swift
//
// Extend the code sample from 6a. Add Facebook Login to Your Code
// Add to your viewDidLoad method:
loginButton.permissions = ["public_profile", "email"]

 

is not registered as a URL scheme. Please add it in your Info.plist' 에러 나는데 원인을 모르겠다...

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함