iOS接入Facebook第三方登錄
開發語言:Swift
官方文檔
第一步 設置開發環境
-
按照官方文檔指引,創建應用
接入Facebook SDK
SDK接入可以選擇cocoapods或者直接下載
第二步 配置info.plist
- 完成
info.plist
列表配置,info.plist
作為源碼打開,復制以下代碼
// 000000000為自己應用的FacebookAppID與URL Schemes
//在官方文檔內可生成
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>fb000000000</string> </array> </dict> </array> <key>FacebookAppID</key> <string>000000000</string> <key>FacebookDisplayName</key> <string>tblogindemo</string>
- 如要使用任何 Facebook 對話框(例如,登錄、分享、應用邀請等),以便從您的應用切換至 Facebook 應用,則您應用程序的 info.plist 還必須包含以下代碼
<key>LSApplicationQueriesSchemes</key> <array> <string>fbapi</string> <string>fb-messenger-share-api</string> <string>fbauth2</string> <string>fbshareextension</string> </array>
第三步 連接應用委托
- 在AppDelegate中添加代碼,啟動時初始化 SDK,并在您執行登錄或分享操作時,讓 SDK 處理通過原生 Facebook 應用獲得的結果。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
//以下方法只支持iOS 9以上
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
let handled = ApplicationDelegate.shared.application(app, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplication.OpenURLOptionsKey.annotation])
return handled
}
第四步 實現功能
- 添加Facebook登錄功能
override func viewDidLoad() {
let loginBtn = FBLoginButton(type: .roundedRect)
loginBtn.center = view.center
view.addSubview(loginBtn)
}
-
檢驗是否成功接入
點擊login按鈕能轉跳至Facebook授權后能返回應用
- 如果你的按鈕變成了logout,那就說明已經登錄成功了
進階
- 單純登錄肯定是不夠了,我這里會把用戶的頭像以及信息顯示出來
- 頭像顯示可以用Facebook封裝好的控件
FBProfilePictureView
,將FBProfilePictureView
的profileID設置為userID即可
Profile.loadCurrentProfile { (currentProfile, error) in
guard let profile = currentProfile else { return }
let userid = profile.userID
let name = profile.name
self.profilePictureView.profileID = userid
self.userDatailsLabel.text = name
}
通過Profile可以獲取用戶信息,包括userID、firstName、middleName、lastName、name
添加測試賬號
-
為你的應用添加管理員、開發者、測試者
我的應用----用戶身份----添加用戶
項目demo
因為這個demo只是用于了解Facebook登錄,并沒有上線,所以請大家將FacebookAppID等修改為自己項目的編號,否則是不可以進行授權登錄的
參考
iOS集成facebook實現自動登錄
尊重原創,轉載請注明出處,謝謝!
未經授權禁止轉載!