今日、facebook SDKをSwiftアプリに統合しようとしましたが、facebookガイドページのクイックスタートでは、古いコードと少し異なります。以下のOBJ-Cコードをswiftに変換するにはどうすればよいですか?
- (void)applicationDidBecomeActive:(UIApplication *)application {
[FBSDKAppEvents activateApp];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
return [[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation];
}
ありがとう!
ブラケットを使用する代わりにドットを使用することを除いて、ほとんど同じです。
func applicationDidBecomeActive(application: UIApplication!) {
FBSDKAppEvents.activateApp()
}
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
pod 'FacebookCore'
pod 'FacebookLogin'
古いSDKからの変更なし
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb$(YOUR_FB_APP_ID)</string>
</array>
</dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
<key>FacebookAppID</key>
<string>$(YOUR_FB_APP_ID)</string>
<key>FacebookDisplayName</key>
<string>$(YOUR_APP_NAME)</string>
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
...
}
func applicationDidBecomeActive(_ application: UIApplication) {
AppEventsLogger.activate(application)
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
let appId = SDKSettings.appId
if url.scheme != nil && url.scheme!.hasPrefix("fb\(appId)") && url.Host == "authorize" { // facebook
return SDKApplicationDelegate.shared.application(app, open: url, options: options)
}
return false
}
...
カスタムコードが含まれていますが、ポイントを取得します
let facebookManager = LoginManager(loginBehavior: .systemAccount, defaultAudience: .everyone)
func loginWithFacebook() {
self.facebookManager.logIn(HAAccountManager.shared.facebookPermissions, viewController: self) { (result) in
switch result {
case .failed(let error):
self.showAlert(forError: error as NSError)
case .cancelled:
print("FB login cancelled")
case .success(let grantedPermissions, let deniedPermissions, let accessToken):
if grantedPermissions.contains(Permission(name: "email")) == true {
ApiClient.shared.facebookSignIn(authToken: accessToken.authenticationToken, completion: { (err, user) in
if err == nil {
// success
}
else {
self.showAlert(forError: err!)
}
})
}
else {
self.showAlert(forError: HAError(title: String(format: String.somethingError, String.signIn), message: grantedPermissions.contains(Permission(name: "email")) == true ? String.noAccountFound : String.missingEmailForSignUp))
}
}
}
}
// custom ex
AppEventsLogger.log(AppEvent(name: "open_app", parameters: ["logged_in": NSNumber(value: HAAccountManager.shared.isUserLoggedIn())], valueToSum: nil))
// purchase ex
AppEventsLogger.log(
AppEvent.purchased(
amount: Double(revenue),
currency: currency,
extraParameters: [
AppEventParameterName.contentId : orderId,
AppEventParameterName.itemCount : order.orderItems.count.nsNumber()
])
)
これはかなり古い質問ですが、Facebookが長い間QuickStartガイドを更新していないため、決して古くなることはありません。
そこで、Swift 4.x.
DidFinishLaunchingで:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FBSDKApplicationDelegate.sharedInstance()?.application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
開いているURLで:
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
let handled = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[.sourceApplication] as? String, annotation: options[.annotation])
return handled
}
IOS 9では次を使用します。
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool
{
FBSDKApplicationDelegate.sharedInstance().application(app, openURL: url, sourceApplication: options["UIApplicationOpenURLOptionsSourceApplicationKey"] as! String, annotation: options["UIApplicationOpenURLOptionsAnnotationKey"])
return true
}
IOS 9では、以下を使用する必要があります。
func application(application: UIApplication,openURL url: NSURL, options: [String: AnyObject]) -> Bool {
return ApplicationDelegate.shared.application(application, openURL: url, sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String, annotation: annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
}
アプリケーションデリゲートが次の注釈を使用してiOS 9で破損する可能性があることを発見しました:options[UIApplicationOpenURLOptionsAnnotationKey]
は、nil値を受け入れないためです。これを空の文字列に設定すると、アプリケーションはfacebookで正常に実行されるはずです。
Swift 2.2ドキュメント:
オプションが非nilの場合、プロパティ、メソッド、またはサブスクリプトを呼び出すオプション値の後に疑問符(?)を配置して、オプションのチェーンを指定します。これは、オプションの値の後に感嘆符(!)を配置して、その値を強制的にアンラップすることに非常に似ています。主な違いは、オプションがnilの場合、オプションのチェーンが正常に失敗するのに対し、オプションがnilの場合、強制的なアンラップはランタイムエラーをトリガーすることです。
if let fbSDKAppId = FBSDKSettings.appID(),
url.scheme!.hasPrefix("fb\(fbSDKAppId)"),
url.Host == "authorize" { // facebook
return FBSDKApplicationDelegate.sharedInstance().application(application,
open: url,
sourceApplication: sourceApplication,
annotation: annotation)
}
IOS 8をサポートしたいので、 Whitney Foster's answer の関数application(_:open:options:)
を変更しました
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
let appId = SDKSettings.appId
if url.scheme != nil && url.scheme!.hasPrefix("fb\(appId)") && url.Host == "authorize" { // facebook
if #available(iOS 9.0, *) {
return SDKApplicationDelegate.shared.application(app, open: url, options: options)
}
}
return false
}
追加のフォールバック機能を実装しました
// Fallback on earlier versions
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return SDKApplicationDelegate.shared.application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
In Swift 3.0.1
return GIDSignIn.sharedInstance().handle(url, sourceApplication:
options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation:
options[UIApplicationOpenURLOptionsKey.annotation])
FBSDKCoreKitを使用したSwift 5(5.3.0)
インポートFBSDKCoreKit appdelegate
DidFinishLaunchingで:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FBSDKCoreKit.ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
開いているURLで:
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
let handled = FBSDKCoreKit.ApplicationDelegate.shared.application(app, open: url, options: options)
return handled
}
For Swift 5 with最新のFBSDK(FBSDKCoreKit 5.2.1))
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
let handled = ApplicationDelegate.shared.application(app, open: url, options: options)
return handled
}