gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:32:36 25 4
gpt4 key购买 nike

在 iOS 中,他们中的大多数通过 SDK 集成了 LinkedIn Login(如果您的 iPhone/iPad 中未安装 LinkedIn App 则无法登录,LinkedIn SDK 会返回一条消息以安装 LinkedIn App)。

但是在 Apple Review 期间,可能有机会拒绝我们的应用程序。所以唯一的解决办法是处理两种情况。

1.使用SDK登录LinkedIn

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

最佳答案

第一步

首先您需要检查您的 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)

}
}

关于ios - 如何在没有SDK的情况下在iOS中集成Linkedin登录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45952362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com