I'm currently implementing a function in SwiftUI to log in with my Instagram account.
It's not working, I'm creating a Firebase Auth function and it comes back to the redirect URL.
This may happen if browser sessionStorage is inaccessible or accidentally cleared. This may happen if browser sessionStorage is inaccessible or accidentally cleared. I get this error.
I can't implement it. I have tried various methods, but all have failed.
If anyone knows how to do this, please help.
import SwiftUI
import AuthenticationServices
import FirebaseAuth
struct InstagramLoginView: View {
var body: some View {
VStack {
Text("Login with Instagram") // タイトル
Button(action: {
// ボタンが押された時にInstagramのログイン処理を開始
InstagramLoginHelper().startInstagramLogin()
}) {
Text("Login with Instagram")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
}
}
}
}
class InstagramLoginHelper: NSObject, ASWebAuthenticationPresentationContextProviding {
func startInstagramLogin() {
let clientID = "XXXXXXXXXXXX"
let redirectURI = "https://XXXXXXXXXXX.firebaseapp.com/__/auth/handler"
let authURL = "https://api.instagram.com/oauth/authorize?client_id=\(clientID)&redirect_uri=\(redirectURI)&scope=user_profile,user_media&response_type=code"
let schem = "XXXXXXXXXXXX"
if let url = URL(string: authURL) {
let session = ASWebAuthenticationSession(url: url, callbackURLScheme: schem) { callbackURL, error in
if let error = error {
print("Error during authentication: \(error.localizedDescription)")
return
}
if let callbackURL = callbackURL, let code = URLComponents(string: callbackURL.absoluteString)?.queryItems?.first(where: { $0.name == "code" })?.value {
// 認証コードを使ってFirebaseでログインする
self.loginWithInstagram(authCode: code)
}
}
session.presentationContextProvider = self
session.start()
}
}
func loginWithInstagram(authCode: String) {
// Firebaseのauthインスタンスを取得
let auth = Auth.auth()
// InstagramのOAuthプロバイダを使用する
let provider = OAuthProvider(providerID: "instagram.com")
// Instagramの認証コードを使って、プロバイダの認証資格情報を生成
provider.getCredentialWith(nil) { credential, error in
if let error = error {
print("Error during authentication: \(error.localizedDescription)")
return
}
if let credential = credential {
// Firebaseにログイン
auth.signIn(with: credential) { authResult, error in
if let error = error {
print("Error during Firebase authentication: \(error.localizedDescription)")
} else {
print("Successfully authenticated with Firebase.")
}
}
}
}
}
// ASWebAuthenticationPresentationContextProvidingの実装
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
return UIApplication.shared.windows.first { $0.isKeyWindow } ?? ASPresentationAnchor()
}
}
#Preview {
InstagramLoginView()
}