카카오톡 로그인 API 설정
https://developers.kakao.com/docs/latest/ko/kakaologin/common
기본 설정은 위의 사이트에 들어가서 한다.
그 외의 파일은 아래 코드를 구현한다.
AppDelegate.swift 코드 구현
import UIKit
import CoreData
import KakaoSDKCommon
import KakaoSDKAuth
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey : Any] = [:]
) -> Bool {
if AuthApi.isKakaoTalkLoginUrl(url) {
return AuthController.handleOpenUrl(url: url)
}
return false
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let nativeAppKey = Bundle.main.infoDictionary?["KAKAO_NATIVE_APP_KEY"] ?? ""
KakaoSDK.initSDK(appKey: nativeAppKey as! String)
return true
}
...
SceneDelegate.swift 코드 구현
import UIKit
import KakaoSDKAuth
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
if let url = URLContexts.first?.url {
if (AuthApi.isKakaoTalkLoginUrl(url)) {
_ = AuthController.handleOpenUrl(url: url)
}
}
}
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow(windowScene: windowScene)
window?.rootViewController = HomeViewController()
window?.makeKeyAndVisible()
}
...
HomeViewController.swift 코드 구현
import UIKit
import KakaoSDKAuth
import KakaoSDKUser
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
checkLoginStatus()
}
func setupUI() {
view.backgroundColor = .white
let logoutButton = UIButton(type: .system)
logoutButton.setTitle("카카오 로그아웃", for: .normal)
logoutButton.addTarget(self, action: #selector(logoutFromKakao), for: .touchUpInside)
logoutButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(logoutButton)
let profileButton = UIButton(type: .system)
profileButton.setTitle("프로필 가져오기", for: .normal)
profileButton.addTarget(self, action: #selector(fetchProfile), for: .touchUpInside)
profileButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(profileButton)
NSLayoutConstraint.activate([
logoutButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
logoutButton.centerYAnchor.constraint(equalTo: view.centerYAnchor),
profileButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
profileButton.topAnchor.constraint(equalTo: logoutButton.bottomAnchor, constant: 20)
])
}
// 초기 로그인 여부를 확인 함수
func checkLoginStatus() {
if !UserApi.isKakaoTalkLoginAvailable() {
let loginVC = LoginViewController()
loginVC.modalPresentationStyle = .overFullScreen
loginVC.delegate = self
present(loginVC, animated: true, completion: nil)
}
}
@objc func logoutFromKakao() {
UserApi.shared.logout { (error) in
if let error = error {
print(error)
} else {
print("logout() success.")
self.checkLoginStatus()
}
}
}
@objc func fetchProfile() {
UserApi.shared.me() { (user, error) in
if let error = error {
print(error)
} else {
print("me() success.")
if let user = user {
print("ID: \(user.id ?? 0)")
print("닉네임: \(user.kakaoAccount?.profile?.nickname ?? "None")")
print("프로필 이미지 URL: \(user.kakaoAccount?.profile?.profileImageUrl?.absoluteString ?? "None")")
}
}
}
}
}
extension HomeViewController: LoginViewControllerDelegate {
func loginViewControllerDidFinish(_ controller: LoginViewController) {
controller.dismiss(animated: true, completion: nil)
}
}
LoginViewController.swift 코드 구현
import UIKit
import KakaoSDKAuth
import KakaoSDKUser
protocol LoginViewControllerDelegate: AnyObject {
func loginViewControllerDidFinish(_ controller: LoginViewController)
}
class LoginViewController: UIViewController {
weak var delegate: LoginViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI() {
view.backgroundColor = UIColor(white: 0, alpha: 0.5)
let containerView = UIView()
containerView.backgroundColor = .white
containerView.layer.cornerRadius = 10
containerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(containerView)
let loginButton = UIButton(type: .system)
loginButton.setTitle("카카오 로그인", for: .normal)
loginButton.addTarget(self, action: #selector(loginWithKakao), for: .touchUpInside)
loginButton.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(loginButton)
NSLayoutConstraint.activate([
containerView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
containerView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
containerView.widthAnchor.constraint(equalToConstant: 300),
containerView.heightAnchor.constraint(equalToConstant: 200),
loginButton.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
loginButton.centerYAnchor.constraint(equalTo: containerView.centerYAnchor)
])
}
@objc func loginWithKakao() {
if UserApi.isKakaoTalkLoginAvailable() {
UserApi.shared.loginWithKakaoTalk { [weak self] (oauthToken, error) in
if let error = error {
print(error)
} else {
print("loginWithKakaoTalk() success.")
_ = oauthToken
self?.delegate?.loginViewControllerDidFinish(self!)
}
}
} else {
UserApi.shared.loginWithKakaoAccount { [weak self] (oauthToken, error) in
if let error = error {
print(error)
} else {
print("loginWithKakaoAccount() success.")
_ = oauthToken
self?.delegate?.loginViewControllerDidFinish(self!)
}
}
}
}
}
'iOS > UIKIT' 카테고리의 다른 글
Custom TabBar 설정 (0) | 2024.06.29 |
---|---|
컬렉션 뷰 설정 (0) | 2024.06.26 |
CollectionView 만들기 (코드로 구현) (1) | 2024.02.25 |
네비게이션 바에 배경 색상 넣기.... (0) | 2024.02.20 |
탭 제스처 + 사진 선택 (0) | 2024.02.02 |