我在 ViewModel 中有以下方法來處理用戶對 Facebook 登錄按鈕的點擊:
import Foundation
import FirebaseAuth
import FacebookLogin
/// A view model that handles login and logout operations.
class SessionStore: ObservableObject {
@Published var user: User?
@Published var isAnon = false
private var handle: AuthStateDidChangeListenerHandle?
private let authRef = Auth.auth()
/// A login manager for Facebook.
private let loginManager = LoginManager()
/// Listens to state changes made by Firebase operations.
func listen() {
handle = authRef.addStateDidChangeListener {[self] (auth, user) in
if user != nil {
self.isAnon = false
self.user = User(id: user!.uid, fbId: authRef.currentUser!.providerData[0].uid, name: user!.displayName!, email: user!.email!, profilePicURL: user!.photoURL)
} else {
self.isAnon = true
self.user = nil
}
}
}
/// Logs the user in using `loginManager`.
///
/// If successful, get the Facebook credential and sign in using `FirebaseAuth`.
///
/// - SeeAlso: `loginManager`.
func facebookLogin() {
loginManager.logIn(permissions: [.publicProfile, .email], viewController: nil) { [self] loginResult in
switch loginResult {
case .failed(let error):
print(error)
case .cancelled:
print("User cancelled login.")
case .success:
let credential = FacebookAuthProvider.credential(withAccessToken: AccessToken.current!.tokenString)
authRef.signIn(with: credential) { (authResult, error) in
if let error = error {
print("Facebook auth with Firebase error: \(error)")
return
}
}
}
}
}
}
在 中listen(),User每當 Firebase 檢測到狀態更改時(即,當用戶登錄時),我都會嘗試構建我的模型。我的User模型很簡單struct:
/// A model for the current user.
struct User: Identifiable, Codable {
var id: String
var fbId: String
var name: String
var email: String
var profilePicURL: URL?
}
問題
現在,正如您在我的listen()方法中看到的,我正在使用 FirebasephotoURL來獲取用戶的個人資料圖片。但是,它只會給我一個低質量的縮略圖。
我很想從 Facebook 獲取普通照片。
我試過的
我試過,在我facebookLogin()打電話GraphRequest來獲取圖片網址。但是,由于我的函式是同步的,我無法將結果存盤到我的User模型中。
I also tried directly using the Graph API link like "http://graph.facebook.com/user_id/picture?type=normal", but it seems like it's no longer the safe/suggested practice.
Question
Given my ViewModel structure, what is the best way to fetch and store Facebook user picture URL to my User model?
uj5u.com熱心網友回復:
我發現,火力地堡的photoURL是Facebook的圖形API網址:http://graph.facebook.com/user_id/picture。因此,要獲得其他大小,我需要做的就是將查詢字串附加?type=normal到photoURL.
要使用GraphRequest,請考慮@jnpdx 的建議:
似乎您至少有幾個選擇:1)使用 GraphRequest 并且在獲得結果之前不要設定您的 User 模型。2) 像現在一樣設定您的 User 模型,然后在您的 GraphRequest 回傳后使用新 URL 更新它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/351173.html
上一篇:添加華為套件時出現“Couldnotfindcom.huawei.hms:location:6.0.0.302”錯誤
