在Swift 3中,要登录Facebook并获取用户的电子邮件地址,你需要使用Facebook SDK。以下是详细的步骤和代码示例,帮助你解决获取空值的问题。
首先,确保你已经在项目中安装了Facebook SDK。你可以使用CocoaPods来安装:
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
然后在终端运行:
pod install
在项目的Info.plist
文件中添加以下内容:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fbYOUR_APP_ID</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>YOUR_APP_ID</string>
<key>FacebookDisplayName</key>
<string>YOUR_APP_NAME</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-share-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
确保将YOUR_APP_ID
和YOUR_APP_NAME
替换为你的Facebook应用的ID和名称。
在你的AppDelegate.swift
文件中初始化Facebook SDK:
import FBSDKCoreKit
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return ApplicationDelegate.shared.application(app, open: url, options: options)
}
在你的ViewController中实现登录和获取用户信息:
import UIKit
import FBSDKLoginKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func loginButtonTapped(_ sender: UIButton) {
let loginManager = LoginManager()
loginManager.logIn(permissions: ["public_profile", "email"], viewController: self) { loginResult in
switch loginResult {
case .success(let grantedPermissions, _, _):
if grantedPermissions.contains("email") {
self.getUserProfile()
}
case .cancelled:
print("User cancelled login.")
case .failed(let error):
print("Login failed with error: \(error.localizedDescription)")
}
}
}
func getUserProfile() {
if let accessToken = AccessToken.current {
GraphRequest(graphPath: "me", parameters: ["fields": "email"]).start { connection, result, error in
if let error = error {
print("Failed to get user profile: \(error.localizedDescription)")
return
}
guard let userData = result as? [String: Any], let email = userData["email"] as? String else {
print("Email is nil")
return
}
print("User email: \(email)")
}
}
}
}
email
权限。你可以在Facebook开发者控制台中检查应用的权限设置。领取专属 10元无门槛券
手把手带您无忧上云