如何在没有SDK的情况下在iOS中集成Linkedin登录?

如何在没有SDK的情况下在iOS中集成Linkedin登录?,ios,objective-c,swift,linkedin,linkedin-api,Ios,Objective C,Swift,Linkedin,Linkedin Api,在iOS中,大多数都通过SDK集成了LinkedIn登录(如果iPhone/iPad中未安装LinkedIn应用程序,则无法登录,LinkedIn SDK将返回消息以安装LinkedIn应用程序) 但在苹果审查期间,可能会有机会拒绝我们的应用程序。 因此,唯一的解决办法是处理两种情况 1.使用SDK登录LinkedIn 2.不使用SDK登录LinkedIn(使用OAuth 2.0)步骤1 首先,你需要检查你的iPhone/iPad中是否安装了LinkedIn应用程序 isInstalled("l

在iOS中,大多数都通过SDK集成了LinkedIn登录(如果iPhone/iPad中未安装LinkedIn应用程序,则无法登录,LinkedIn SDK将返回消息以安装LinkedIn应用程序)

但在苹果审查期间,可能会有机会拒绝我们的应用程序。 因此,唯一的解决办法是处理两种情况

1.使用SDK登录LinkedIn


2.不使用SDK登录LinkedIn(使用OAuth 2.0)

步骤1

首先,你需要检查你的iPhone/iPad中是否安装了LinkedIn应用程序

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://”)


您好@eld您有什么pod或sdk吗?如果有,请给我链接我有两种登录方法1。使用SDK 2登录LinkedIn。没有SDK的LinkedIn登录(使用OAuth 2.0)对于第一种方法,我在我的应用程序中使用LinkedIn SDK。对于第二种方法,我们不需要任何SDK或Pod文件。我想使用它登录并获取一些基本的配置文件详细信息,包括电子邮件名称、链接,如果手机中安装了应用程序,它应该打开应用程序并获取详细信息,否则它应该在webview中打开并获取详细信息,我必须使用哪种方法fllow@SatheeshkumarNaidu你需要电子邮件、姓名等详细信息,链接等。。。。你可以选择任何一种方法。我选择了,因为如果用户没有安装LinkedIn应用程序。那样的话,我们需要细节。因此,我们通过API获取详细信息。LinkedIn SDK的好处是,如果用户已经登录LinkedIn应用程序,则用户无需再次登录。缺点是Linkedin SDK增加了应用程序的大小。最初,如果提供了支持,,,我想,,,现在停止了SDK支持
request.url?.host == "com.elsner.linkedin.oauth" // Change this to

request.url?.host == "your callback url's host"