Integrating linkedin in ios App for getting some d

2019-08-23 18:45发布

I am working on the linkedin based signup,I want to get the some profile details from linkedin. If user has already linkedin installed in your it should open the app and get the details if not you should open the web view and get the details. I downloaded sdk from developers.linkedin.com and I am using the below code.

@IBAction func Signup(_ sender: UIButton) {

    if (self.isInstalled(appScheme: "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!.instantiateViewController(withIdentifier: "LinkedinWebVC") as UIViewController
        self.navigationController?.pushViewController(webViewCnt, animated: true)

    }

}

using this i am checking the App installed or not if not i am presenting the webview controller and nin that I am using the below code

 let linkedInKey = "815972uscqupkz"

let linkedInSecret = "MuWBM6SQOQrBosol"

let authorizationEndPoint = "https://www.linkedin.com/uas/oauth2/authorization"

let accessTokenEndPoint = "https://www.linkedin.com/uas/oauth2/accessToken"
override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.isNavigationBarHidden = false
    self.navigationController?.navigationBar.isTranslucent = false
    Webviewobj.delegate = self
    self.startAuthorization()
  //   let redirectURL = "https://com.appcoda.linkedin.oauth/oauth".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    // Do any additional setup after loading the view.
}
func startAuthorization() {
    let responseType = "code"
    let redirectURL = "https://jobz.com".addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!

    let state = "E3ZYKC1T6H2yP4zyEy8xIdB4qSMnhfxsdxshcdggdxgqVP7502" /// "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 = URLRequest(url: URL(string: authorizationURL)!)
    Webviewobj.loadRequest(request)




}

func logout(){
    let revokeUrl = "https://api.linkedin.com/uas/oauth/invalidateToken"
        let request = URLRequest(url: URL(string: revokeUrl)!)
   Webviewobj.loadRequest(request)
}

private func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    let url = request.url!
    if url.host == "http://jobz.com" {
       //rangeOfString("code")
        if url.absoluteString.range(of: "code") != nil {
            let urlParts = url.absoluteString.components(separatedBy: "?")   //componentsSeparatedByString("?")
            let code = urlParts[1].components(separatedBy: "=")[1]
            //componentsSeparatedByString("=")[1]
            requestForAccessToken(authorizationCode: code)
          //  requestForAccessToken(code)
        }

    }

    return true
}
private func webViewDidFinishLoad(webView : UIWebView) {

}
func requestForAccessToken(authorizationCode: String) {
    let grantType = "authorization_code"

    let redirectURL = "https://jobz.com".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!


    // 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.data(using: String.Encoding.utf8)

    // Initialize a mutable URL request object using the access token endpoint URL string.
    let request = NSMutableURLRequest(url: NSURL(string: accessTokenEndPoint)! as URL)

    // 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 = URLSession(configuration: URLSessionConfiguration.default)

    // Make the request.
    let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
        // Get the HTTP status code of the request.
        let statusCode = (response as! HTTPURLResponse).statusCode

        if statusCode == 200 {
            // Convert the received JSON data into a dictionary.
            do {
                let dataDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String, Any>
                print("dataDictionary\(dataDictionary)")
                let accessToken = dataDictionary["access_token"] as! String

                UserDefaults.standard.set(accessToken, forKey: "LIAccessToken")
                UserDefaults.standard.synchronize()
                print("START sentData")
                DispatchQueue.main.async {
                self.navigationController?.popViewController(animated: true)
                }

            }
            catch {
                print("Could not convert JSON data into a dictionary.")
            }
        }else{
            print("cancel clicked")
        }
    }

    task.resume()
}

the linked website is opening in the webview if i give all the credentials and click on the login it shows their ,no delegates are getting called and in the log i am getting the below error The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in may also be helpful. 2018-06-01 15:10:51.499017+0530 JobzTop Assessor[19856:3088129] CredStore - performQuery - Error copying matching creds. Error=-25300,

query={
class = inet;
"m_Limit" = "m_LimitAll";
ptcl = htps;
"r_Attributes" = 1;
sdmn = "Password Protected Area";
srvr = "jobz.com";
sync = syna;
}

if copy the request url and past it in the chrome the linkedin login page is opening and if i give details and hit on signin its open my host url in thw webpage. Please find the below attached images. modilewebview chrome after pasting url which i am using webview request opens the linkedin page and after login i am getting this

0条回答
登录 后发表回答