在ios App中集成linkedin以获取一些细节

时间:2018-06-01 09:53:22

标签: ios swift uiwebview linkedin

我正在进行基于linkedin的注册,我想从linkedin获取一些个人资料详细信息。 如果用户已经安装了您的应用程序,则应该打开应用程序并获取详细信息,否则您应该打开Web视图并获取详细信息。 我从developers.linkedin.com下载了sdk,我使用的是以下代码。

@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)

    }

}

使用这个我正在检查已安装的应用程序,如果不是我正在呈现webview控制器并且我正在使用以下代码

 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()
}

链接的网站在webview中打开如果我提供所有凭据并点击它显示的登录信息,没有代表被调用,在日志中我收到以下错误 在列出的UIView上的UIConstraintBasedLayoutDebugging类别中的方法也可能有所帮助。 2018-06-01 15:10:51.499017 + 0530 JobzTop Assessor [19856:3088129] CredStore - performQuery - 错误复制匹配的信用卡。错误= -25300,

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

如果复制请求网址并在Chrome中通过它,则会打开linkedin登录页面,如果我提供详细信息并点击登录,则在该网页中打开我的主机网址。 请查看以下附件图片。 modilewebview chrome after pasting url which i am using webview request opens the linkedin page and after login i am getting this

0 个答案:

没有答案