Вы уже создали и настроили приложение facebook? Вы можете сделать это здесь https://developers.facebook.com/apps/:
- Создать приложение> установить отображаемое имя > Создайте идентификатор приложения
- , затем вам нужно go в Настройки> Basi c> прокрутить вниз до появления Добавить платформу и выбрать iOS
- поставить идентификатор пакета вашего iOS Project (который вы можете найти в вашем Xcode> Project> Target> Bundle Identifier) и включите Single Sign ON, затем выполните Save Changes
- Roles> Test Users> Add> Create Test User> Edit> Change name / пароль и введите пароль, который вы запомните
Обратите внимание на тестового пользователя email
и password
, чтобы вы могли отлаживать свое приложение. В Настройках> Basi c запишите App ID
и Display Name
, чтобы добавить их в свой Info.plist позже.
Убедитесь, что вы добавили в свой подфайл :
pod 'FacebookCore'
pod 'FacebookLogin'
Затем выполните pod install
в терминале (если вы еще не установили оба модуля).
В вашем AppDelegate.swift вы должны иметь это как минимум:
import UIKit
import FacebookLogin
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
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
)
}
}
Щелкните правой кнопкой мыши на Info.plist и откройте как> Исходный код, вставьте его перед </dict>
:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb{your-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-name}
(один раз , с отображаемым именем приложения, которое вы ранее отмечали на панели инструментов приложения Facebook), и {your-app-id}
(дважды, также вы приняли это к сведению на первом шаге с панели приложения Facebook) в приведенном выше фрагменте.
Теперь go для вашего ViewController.swift:
import UIKit
import FacebookLogin
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if AccessToken.current != nil {
// Already logged-in
// Redirect to Home View Controller
goToHome()
}
// Add LoginButton
let loginButton = FBLoginButton(permissions: [ .publicProfile, .email, .userFriends ])
let screenSize:CGRect = UIScreen.main.bounds
let screenHeight = screenSize.height // real screen height
//let's suppose we want to have 10 points bottom margin
let newCenterY = screenHeight - loginButton.frame.height - 20
let newCenter = CGPoint(x: view.center.x, y: newCenterY)
loginButton.center = newCenter
view.addSubview(loginButton)
// Triggered after every successfully login / logout
NotificationCenter.default.addObserver(forName: .AccessTokenDidChange, object: nil, queue: OperationQueue.main) { [weak self] _ in
if AccessToken.current != nil {
// Successfully just Logged in
// Redirect to Home View Controller
self?.goToHome()
} else {
// Successfully just Logged out
}
}
}
func goToHome() {
let storyboard = UIStoryboard(name: "HomeAfterLogIn", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "HomeAfterLogInViewController") // I called mine like that (check screenshot below)
self.navigationController?.pushViewController(vc, animated: true)
}
}
Убедитесь, что ViewController вашего HomeAfterLogIn.storyboard (который я не уверен, с каким ***ViewController.swift
вы связали его) имеет HomeAfterLogIn Stoyboard ID
. В конце концов он также должен быть связан с файлом ***ViewController.swift
, имя которого совпадает с идентификатором для простоты (например, HomeAfterLogIn.swift).
В моем примере я назвал их HomeAfterLogInViewController
, как вы можете видеть в этом снимок экрана, файл HomeAfterLogInViewController.swift
и файл HomeAfterLogInViewController Storyboard ID
, но я сохранил имя файла раскадровки как HomeAfterLogIn.storyboard
. 
Если вы не встраивали свой ViewController
в Main.storyboard
(я полагаю, он у вас есть) в NavigationController
, тогда вы должны сделать это для заставить его работать, вставляя в стек навигации другой контроллер вида, например Home ... ViewController.
Вы можете сделать это следующим образом: нажмите ViewController на главной панели, а затем в меню вверх go до Editor > Embed In > Navigation Controller
:
