[英]How to integrate Linkedin Login in iOS Without SDK?
在 iOS 中,大多數都通過 SDK 集成了 LinkedIn 登錄(如果您的 iPhone/iPad 中未安裝 LinkedIn App,則您無法登錄,LinkedIn SDK 會返回一條消息以安裝 LinkedIn App)。
但是在 Apple Review 期間,可能有機會拒絕我們的應用程序。 所以唯一的解決辦法是處理兩種情況。
1.LinkedIn使用SDK登錄
2.LinkedIn 無需 SDK 登錄(使用 OAuth 2.0)
第 1 步
首先,您需要檢查您的 iPhone/iPad 中是否安裝了 LinkedIn App。
isInstalled("linkedin://app") // function call
func isInstalled(appScheme:String) -> Bool{
let appUrl = NSURL(string: appScheme)
if UIApplication.sharedApplication().canOpenURL(appUrl! as NSURL)
{
return true
} else {
return false
}
}
第 2 步
創建一個 webviewController.swift
import UIKit
class WebViewController: UIViewController,UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
let linkedInKey = "xxxxxx"
let linkedInSecret = "xxxxxx"
let authorizationEndPoint = "https://www.linkedin.com/uas/oauth2/authorization"
let accessTokenEndPoint = "https://www.linkedin.com/uas/oauth2/accessToken"
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
self.startAuthorization()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func startAuthorization() {
let responseType = "code"
let redirectURL = "https://com.appcoda.linkedin.oauth/oauth".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet())!
let state = "linkedin\(Int(NSDate().timeIntervalSince1970))"
let scope = "r_basicprofile,r_emailaddress"
var authorizationURL = "\(authorizationEndPoint)?"
authorizationURL += "response_type=\(responseType)&"
authorizationURL += "client_id=\(linkedInKey)&"
authorizationURL += "redirect_uri=\(redirectURL)&"
authorizationURL += "state=\(state)&"
authorizationURL += "scope=\(scope)"
// logout already logined user or revoke tokens
logout()
// Create a URL request and load it in the web view.
let request = NSURLRequest(URL: NSURL(string: authorizationURL)!)
webView.loadRequest(request)
}
func logout(){
let revokeUrl = "https://api.linkedin.com/uas/oauth/invalidateToken"
let request = NSURLRequest(URL: NSURL(string: revokeUrl)!)
webView.loadRequest(request)
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let url = request.URL!
if url.host == "com.appcoda.linkedin.oauth" {
if url.absoluteString!.rangeOfString("code") != nil {
let urlParts = url.absoluteString!.componentsSeparatedByString("?")
let code = urlParts[1].componentsSeparatedByString("=")[1]
requestForAccessToken(code)
}
}
return true
}
func requestForAccessToken(authorizationCode: String) {
let grantType = "authorization_code"
let redirectURL = "https://com.appcoda.linkedin.oauth/oauth".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet())!
// Set the POST parameters.
var postParams = "grant_type=\(grantType)&"
postParams += "code=\(authorizationCode)&"
postParams += "redirect_uri=\(redirectURL)&"
postParams += "client_id=\(linkedInKey)&"
postParams += "client_secret=\(linkedInSecret)"
// Convert the POST parameters into a NSData object.
let postData = postParams.dataUsingEncoding(NSUTF8StringEncoding)
// Initialize a mutable URL request object using the access token endpoint URL string.
let request = NSMutableURLRequest(URL: NSURL(string: accessTokenEndPoint)!)
// Indicate that we're about to make a POST request.
request.HTTPMethod = "POST"
// Set the HTTP body using the postData object created above.
request.HTTPBody = postData
// Add the required HTTP header field.
request.addValue("application/x-www-form-urlencoded;", forHTTPHeaderField: "Content-Type")
// Initialize a NSURLSession object.
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
// Make the request.
let task: NSURLSessionDataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
// Get the HTTP status code of the request.
let statusCode = (response as! NSHTTPURLResponse).statusCode
if statusCode == 200 {
// Convert the received JSON data into a dictionary.
do {
let dataDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
print("dataDictionary\(dataDictionary)")
let accessToken = dataDictionary["access_token"] as! String
NSUserDefaults.standardUserDefaults().setObject(accessToken, forKey: "LIAccessToken")
NSUserDefaults.standardUserDefaults().synchronize()
print("START sentData")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.navigationController?.popViewControllerAnimated(true)
})
}
catch {
print("Could not convert JSON data into a dictionary.")
}
}else{
print("cancel clicked")
}
}
task.resume()
}
}
第 3 步
LinkedIn登錄按鈕點擊
@IBAction func linkedinButtonClicked(sender: AnyObject) {
if (self.isInstalled("linkedin://app")){
// App installed
let permissions = [LISDK_BASIC_PROFILE_PERMISSION,LISDK_EMAILADDRESS_PERMISSION]
print("persmission end")
LISDKSessionManager.createSessionWithAuth(permissions, state: nil, showGoToAppStoreDialog: true, successBlock: { (returnState) -> Void in
let session = LISDKSessionManager.sharedInstance().session
LISDKAPIHelper.sharedInstance().getRequest("https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,picture-url,public-profile-url,industry,positions,location)?format=json", success: { (response) -> Void in
if let data = response.data.dataUsingEncoding(NSUTF8StringEncoding) {
if let dictResponse = try? NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers){
print("success")
}
}
}, error: { (error) -> Void in
print("LINKEDIN error\(error)")
})
}) { (error) -> Void in
print("error login linkedin")
}
}else{
// App not installed
print("App is not installed")
isBackFromWebViewCntr = true
let webViewCnt = self.storyboard!.instantiateViewControllerWithIdentifier("WebViewController") as UIViewController
self.navigationController?.pushViewController(webViewCnt, animated: true)
}
}
很遺憾,連LinkedIn都沒有提供這個問題的文檔或示例項目,我瀏覽了這么多網頁,終於在這個鏈接中找到了一些有用的東西。 該網站提供教程和示例代碼。 下載示例代碼並替換在您的 LinkedIn 開發人員門戶中生成的以下值
let linkedInKey = "your LinkedIn key"
let linkedInSecret = "your LinkedIn secret"
let callBackURL = "your callback url"
在 WKNavigationDelegate 中,將主機 url 替換為您的主機 url(在我的情況下,它的回調 url 沒有“https://”)
request.url?.host == "com.elsner.linkedin.oauth" // Change this to
request.url?.host == "your callback url's host"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.