pod 'naveridlogin-sdk-ios'
pod 'Alamofire'
로그인 버튼과 로그아웃 버튼, 로그인이 완료됐을 때 보여질 이름, 이메일, 아이디(id) 라벨
Project의 Targets에서 Info를 선택
URL Types를 열고 다음과 같이 추가한다
URL Schemes의 이름은 소문자로 해야 한다

URL Scheme에 위에서 설정한 URL Scheme을 쓴다Client ID와 Client Secret이 있다Info.plist에 다음과 같이 추가한다
근데 이거 없어도 잘 동작하던데...
AppDelegate.swift에 NaverThirdPartyLogin를 import한다AppDelegate.swift의 아무 곳에다가 kServiceAppUrlScheme라고 쓰고 Jump to Definition한다(아무 곳에 쓴 것은 다시 지워주자)
kServiceAppUrlScheme에는 만들어두었던 URL SchemekConsumerKey에는 NAVER Developer에 등록했을 때 받았던 Client IDkConsumerSecret에는 NAVER Developer에 등록했을 때 받았던 Client SecretkServiceAppName에는 하고 싶은 이름AppDelegate.swift에 NaverThirdPartyLogin를 import한다import UIKit
import NaverThirdPartyLogin
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// MARK: 네이버 로그인
let instance = NaverThirdPartyLoginConnection.getSharedInstance()
// 네이버 앱으로 인증 방식 활성화
instance?.isNaverAppOauthEnable = true
// SafariViewController로 인증 방식 활성화
instance?.isInAppOauthEnable = true
// 아이폰에서 인증 화면을 세로모드에서만 적용
instance?.isOnlyPortraitSupportedInIphone()
// 미리 만들어두었던 URL Scheme
instance?.serviceUrlScheme = kServiceAppUrlScheme
// 등록한 애플리케이션의 Client ID
instance?.consumerKey = kConsumerKey
// 등록한 애플리케이션의 Client Secret
instance?.consumerSecret = kConsumerSecret
// 앱 이름
instance?.appName = kServiceAppName
// -> 위에서 상수 설정할 때 했던거임
return true
}
// MARK: 네이버 로그인
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
NaverThirdPartyLoginConnection.getSharedInstance().application(app, open: url, options: options)
return true
}
}
SceneDelegate.swift에 작성하자// 네이버 로그인 화면이 새로 등장 -> 토큰을 요청하는 코드
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
NaverThirdPartyLoginConnection
.getSharedInstance()
.receiveAccessToken(URLContexts.first?.url)
}
import UIKit
import NaverThirdPartyLogin
import Alamofire
class ViewController: UIViewController {
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var idLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
let loginInstance = NaverThirdPartyLoginConnection.getSharedInstance()
override func viewDidLoad() {
super.viewDidLoad()
loginInstance?.delegate = self
}
@IBAction func login(_ sender: UIButton) {
loginInstance?.requestThirdPartyLogin()
}
@IBAction func logout(_ sender: UIButton) {
loginInstance?.requestDeleteToken()
}
// MARK: 회원 프로필 조회 API
func getInfo() {
guard let isValidAccessToken = loginInstance?.isValidAccessTokenExpireTimeNow() else { return }
if !isValidAccessToken {
return
}
guard let tokenType = loginInstance?.tokenType else { return }
guard let accessToken = loginInstance?.accessToken else { return }
let urlStr = "https://openapi.naver.com/v1/nid/me"
let url = URL(string: urlStr)!
let authorization = "\(tokenType) \(accessToken)"
let req = AF.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: ["Authorization": authorization])
req.responseJSON { response in
guard let result = response.value as? [String: Any] else { return }
guard let object = result["response"] as? [String: Any] else { return }
guard let name = object["name"] as? String else { return }
guard let email = object["email"] as? String else { return }
guard let id = object["id"] as? String else { return }
print(email)
self.nameLabel.text = "\(name)"
self.emailLabel.text = "\(email)"
self.idLabel.text = "\(id)"
}
}
}
// MARK: - NaverThirdPartyLoginConnectionDelegate
extension ViewController: NaverThirdPartyLoginConnectionDelegate {
// 로그인에 성공한 경우 호출
func oauth20ConnectionDidFinishRequestACTokenWithAuthCode() {
print("로그인 성공!!")
getInfo()
}
// refresh token
func oauth20ConnectionDidFinishRequestACTokenWithRefreshToken() {
print("리프레시 토큰")
getInfo()
}
// 로그아웃
func oauth20ConnectionDidFinishDeleteToken() {
print("로그아웃")
getInfo()
}
// 모든 에러 처리
func oauth20Connection(_ oauthConnection: NaverThirdPartyLoginConnection!, didFailWithError error: Error!) {
print("---ERROR: \(error.localizedDescription)---")
}
}