Swift中Firebase Auth谷歌登录后photoURL始终返回null的问题
问题原因
Firebase Auth通过谷歌凭证登录时,只会自动同步邮箱这类基础身份信息,不会默认把谷歌用户的头像URL同步到Firebase用户记录的photoURL字段,所以你后续调用Auth.auth().currentUser?.photoURL会返回null。
解决方法
在登录成功的回调里,拿到谷歌用户的头像URL后,手动调用Firebase的updateProfile方法更新用户资料,这样后续就能通过currentUser获取到头像URL了。
修改后的登录代码示例:
private func authenticateUser(for user: GIDGoogleUser?, with error: Error?) { if let error = error { print(error.localizedDescription) return } guard let user = user, let idToken = user.idToken?.tokenString else { return } let credential = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: user.accessToken.tokenString) Auth.auth().signIn(with: credential) { [unowned self] (authResult, error) in if let error = error { print(error.localizedDescription) } else { // 1. 拿到谷歌用户的头像URL guard let googleAvatarUrl = user.profile?.imageURL(withDimension: 36)?.absoluteString, let currentUser = Auth.auth().currentUser else { return } // 2. 创建用户资料更新请求 let profileChangeRequest = currentUser.createProfileChangeRequest() profileChangeRequest.photoURL = URL(string: googleAvatarUrl) // 3. 提交更新 profileChangeRequest.commitChanges { error in if let error = error { print("更新用户资料失败:\(error.localizedDescription)") } else { print("用户资料更新成功,头像已同步") // 此时再打印currentUser的photoURL就有值了 print(currentUser.photoURL?.absoluteString ?? "") } } } } }
之后在视图中调用print(user?.photoURL?.absoluteString ?? "")就能正常获取到头像URL了。
内容的提问来源于stack exchange,提问作者user2343632
相关产品推荐
相关产品推荐

