2017-08-30 30 views
1

在iOS中,他們大部分集成了LinkedIn通過SDK登錄(如果LinkedIn App沒有安裝在您的iPhone/iPad上,您無法登錄,LinkedIn SDK會返回一條消息來安裝LinkedIn App)。如何集成Linkedin登錄iOS沒有SDK?

但在Apple Review期間,可能有機會拒絕我們的應用程序。 所以唯一的解決辦法是處理兩種情況。

1.LinkedIn登錄隨着SDK

2.LinkedIn登錄無需SDK(使用OAuth 2.0)

回答

1

步驟1

首先,你需要檢查LinkedIn應用程序被安裝或沒有在您的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 
    } 

} 

步驟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) 

    } 
}