Schritt 1
Zuerst müssen Sie LinkedIn App überprüfen installiert ist oder nicht in Ihrem iPhone/iPad.
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
}
}
Schritt 2
erstellen 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()
}
}
Schritt 3
LinkedIn Login-Button klicken
@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)
}
}