Swift 4.0 目前改用cocoaPods來整合facebook功能

1建立你的FacebookApp

從https://developers.facebook.com/apps 登入並建立你的app

2.安裝Facebook SDK use cocoaPods

安裝好cocoaPods後切換到Xcode專案目錄於Terminal下以下指令

pod init

若初始化成成會於專案資料夾下多一個Podfile檔案

使用文字編輯器打開加入以下指令

pod 'FacebookCore'
pod 'FacebookLogin'
pod 'FacebookShare'

儲存後離開此檔案,於Terminal下達指令

pod install

安裝好後,記得執行更新動作,因為FB SDK更新過版本,所以要記得執行更新否則專案會有錯誤發生

pod update

更新好後,就可以開啟xcworkspace而不是利用xcodeproj開啟

3.設定你的info.plist檔案

於</dict>前加入以下xml

<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>

4.設定App Delegate

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        // Override point for customization after application launch.

        SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)

       

        return true

    }

 

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

        let appId: String = SDKSettings.appId

        if url.scheme != nil && url.scheme!.hasPrefix("fb\(appId)") && url.host ==  "authorize" {

            return SDKApplicationDelegate.shared.application(app, open: url, options: options)

        }

       

        return false

    }

 

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.

        AppEventsLogger.activate(application)

    }

5.登入程式

let loginManager = LoginManager()

        loginManager.logIn(readPermissions: [.publicProfile,.email,.userFriends], viewController: self) { (loginResult) in

            switch loginResult{

            case .failed(let error):

                print(error)

            //失敗的時候回傳

            case .cancelled:

                print("the user cancels login")

            //取消時回傳內容

            case .success(grantedPermissions: _, declinedPermissions: _, token: _):

//                self.getDetails()

                print("user log in")

                //成功時print("user log in")

                self.title = "FBLogin"

            }

        }

6.登出程式

let loginManager = LoginManager()

        loginManager.logOut()

        

        if AccessToken.current != nil{

            print("login")

        }else{

            print("logout")

 

        }

}

 

 

創作者介紹
創作者 狼翔月影 的頭像
狼翔月影

狼翔天地

狼翔月影 發表在 痞客邦 留言(0) 人氣()