在 Swift 应用程序中集成 LinkedIn 登录
首先,下载LinkedIn iOS SDK。我将在这个例子中使用 1.07 稳定版。我将遵循集成指南here。
- 创建一个新的Developer Application。
- 将您的 iOS 应用程序包标识符添加到移动设备下的 LinkedIn 应用程序。
- 将您的 LinkedIn 应用 ID 和 URL 方案添加到应用的 Info.plist 文件中。
- 将指定的 LinkedIn URL 方案和 ATS URL 列入白名单。
- 将
linkedin-sdk.framework 库复制到您的应用程序。确保选中“必要时复制文件”和“为文件夹引用创建组”。
项目设置完成,现在开始编写代码吧!
创建一个名为BridgingHeader.h 的新头文件。在 Targets -> YourApp -> Build Settings -> Swift Compiler - Code Generation 下,将 MyApp/BridgingHeader.h 添加到“Objective-C Bridging Header”。
在您的BridgingHeader.h 中,添加以下两行:
#import <Foundation/Foundation.h>
#import <linkedin-sdk/LISDK.h>
在您的 AppDelegate.swift 中,添加以下代码来处理 OAuth URL 回调:
斯威夫特 3:
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
if LISDKCallbackHandler.shouldHandle(url) {
return LISDKCallbackHandler.application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
return true
}
Swift 2.x:
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
if LISDKCallbackHandler.shouldHandleUrl(url) {
return LISDKCallbackHandler.application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
return true
}
现在是时候登录用户了。在您的视图控制器中,假设您有一个“登录”按钮。您的 IBAction 可能如下所示:
@IBAction func doLogin(sender: AnyObject) {
LISDKSessionManager.createSessionWithAuth([LISDK_BASIC_PROFILE_PERMISSION], state: nil, showGoToAppStoreDialog: true, successBlock: { (returnState) -> Void in
print("success called!")
let session = LISDKSessionManager.sharedInstance().session
}) { (error) -> Void in
print("Error: \(error)")
}
}
登录时,将要求用户通过您的应用程序进行身份验证:
如果用户允许,将调用成功块,您可以获取有关经过身份验证的用户的信息。如果登录失败或用户不允许访问,则会调用失败块,您可以提醒用户发生的问题。
要获取我们通过身份验证的用户的信息,请在用户的个人资料上调用 GET 请求:
let url = "https://api.linkedin.com/v1/people/~"
if LISDKSessionManager.hasValidSession() {
LISDKAPIHelper.sharedInstance().getRequest(url, success: { (response) -> Void in
print(response)
}, error: { (error) -> Void in
print(error)
})
}
response.data 将包含有关经过身份验证的用户的信息:
"{\n \"firstName\": \"Josh\",\n \"headline\": \"Senior Mobile Engineer at A+E Networks\",\n ... }"
进一步阅读docs,了解您可以使用 API 做的更多事情。
可以在here找到一个示例项目(我的 App ID 被混淆了)。