我正在尝试以 swift 实现 facebook 登录。我目前遇到错误
The operation couldn’t be completed. (com.facebook.sdk.core error 3.)
我目前的实现如下:
我的 Pod 文件:
target 'AlamofireTest' do
# Comment the next line if you're not using Swift and don't want to use
dynamic frameworks
use_frameworks!
# Pods for AlamofireTest
pod 'Alamofire'
pod 'AlamofireImage'
pod 'FBSDKLoginKit'
target 'AlamofireTestTests' do
inherit! :search_paths
# Pods for testing
end
target 'AlamofireTestUITests' do
inherit! :search_paths
# Pods for testing
end
end
我的Appdelegate文件:
import UIKit
import FBSDKCoreKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FBSDKApplicationDelegate.sharedInstance()?.application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
let handled = FBSDKApplicationDelegate.sharedInstance()?.application(app, open: url, options: options)
return handled!
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
和我的 ViewController 实现:
@IBAction func loginWithFacebook(_ sender: Any) {
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
fbLoginManager.logIn(withReadPermissions: ["public_profile","email"], from: self) { (result, error) -> Void in
if error != nil {
print(error!.localizedDescription)
self.dismiss(animated: true, completion: nil)
} else if result!.isCancelled {
print("Cancelled")
self.dismiss(animated: true, completion: nil)
} else {
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, relationship_status"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
let fbDetails = result as! NSDictionary
print(fbDetails)
}
})
}
}
}
我已按照指南facebook登录ios中提到的步骤进行操作,并且还使用了this中的建议。我找不到步骤,我做错了。非常感谢任何帮助。
导入SDK:
在Appdelegate.swift中
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool
{
return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
在ViewController.swift中
@IBAction func ButtonClickFB(_ sender: Any){
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.logOut()
fbLoginManager.logIn(withReadPermissions:["email","user_friends","user_birthday"], from: self, handler: { (result, error) -> Void in
if ((error) != nil)
{
// Process error
// print(error)
}
else if (result?.isCancelled)!
{
// Handle cancellations
// print(error)
}
else
{
let fbloginresult : FBSDKLoginManagerLoginResult = result!
if(fbloginresult.grantedPermissions.contains("email"))
{
self.getFBUserData()
// fbLoginManager.logOut()
}
}
})
}
func getFBUserData () {
if((FBSDKAccessToken.current()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(normal), email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
print((result! as AnyObject))
// print(((result! as AnyObject).value(forKey: "id") as? String)!)
self.strEmail = ((result! as AnyObject).value(forKey: "email") as? String) ?? ""
self.strID = ((result! as AnyObject).value(forKey: "id") as? String) ?? ""
self.strName = ((result! as AnyObject).value(forKey: "name") as? String) ?? ""
self.TextFBEmail.text = self.strEmail
}
})
}
}
将此添加到信息中
在info.plist中添加FB id
在 Facebook Console 上创建项目并获取密钥和 URL Schme。
修改Info.plist,
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb17996xxxxxxx</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>179962xxxxxx</string>
<key>FacebookDisplayName</key>
<string>Restman</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-share-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
更改 AppDelegate,
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
let handled = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation: options[UIApplicationOpenURLOptionsKey.annotation])
return handled
}
在你看来,
FacebookLoginHelper.shared.authenticate(view: self) { (isLoggedIn) in
if isLoggedIn {
FacebookLoginHelper.shared.getUserProfile(onCompletion: { (user) in
print(user)
})
}
}
//
// FacebookLoginHelper.swift
// FacebookSigInDemo
//
// Created by Brahma on 04/02/23.
//
import Foundation
import FBSDKCoreKit
import FBSDKLoginKit
struct FacebookUser {
var name: String!
var email: String!
var userID: String!
var imagePath: String?
}
class FacebookLoginHelper {
private let manager = FBSDKLoginManager()
private let facebookKeys = ["public_profile", "email"]
private let graphDict = ["fields": "id, name, picture.type(large), email"]
public static let shared = FacebookLoginHelper()
private func prepareUser(dict:[String:Any]) -> FacebookUser {
var user = FacebookUser()
user.name = dict["name"] as? String
user.email = dict["email"] as? String
user.userID = dict["id"] as? String
return user
}
public func authenticate(view: UIViewController, onCompletion:@escaping (Bool)->()) {
manager.logIn(withReadPermissions: facebookKeys, from: view) { (result, error) in
if let status = result {
if !status.isCancelled {
//onSuccess
onCompletion(true)
}
//onFail
onCompletion(false)
}
}
}
public func getUserProfile(onCompletion:@escaping (FacebookUser)->()) {
if FBSDKAccessToken.current() != nil {
FBSDKGraphRequest(graphPath: "me", parameters: graphDict).start { (connection, result, error) in
if let dict = result as? [String:Any] {
let user = self.prepareUser(dict: dict)
onCompletion(user)
}
}
}
else {
//onError
}
}
public func logout() {
manager.logOut()
}
}
我收到错误 - 应用程序未激活:此应用程序当前无法访问,应用程序开发人员已意识到该问题。当应用程序重新激活时,您将能够登录。