使用 Swift 在LinkedIn上共享(无 SDK)



虽然我见过许多在LinkedIn上共享的解决方案,但是如果不使用LISDKAPIHelper,我就找不到任何解决方案。

这是我的场景。 我有有效的访问令牌,我已经使用它从用户配置文件中检索信息。以下是我一直尝试使用该令牌发布的步骤。我一直收到"状态代码 = 400"。可能是我对请求URL做错了什么。

谁能在这方面帮助我?

这是我的代码....

@IBAction func btnPostOn(_ sender: UIButton) {
print("btnPostOn pressed")

if let accessToken = UserDefaults.standard.object(forKey: "LIAccessToken") {
// Specify the URL string that we'll get the profile info from.
let targetURLString = "https://api.linkedin.com/v1/people/~/shares"
let payloadStr: String = "{"comment":"Check out developer.linkedin.com!","visibility":{"code":"anyone"}}"
// Initialize a mutable URL request object.
let request = NSMutableURLRequest(url: NSURL(string: targetURLString)! as URL)
// Indicate that this is a GET request.
request.httpMethod = "POST"
request.httpBody = payloadStr.data(using: String.Encoding.utf8)
// Add the access token as an HTTP header field.
request.addValue("Bearer (accessToken)", forHTTPHeaderField: "Authorization")
// Make the request.
let task: URLSessionDataTask = URLSession.shared.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.
guard let json = (try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
print("Not containing JSON")
return
}

////To do////

}
}
task.resume()
}
}

最后,我找到了适合我的解决方案。我一直做错的事情是制作我的请求标头。它对我有用。

if let accessToken = UserDefaults.standard.object(forKey: "LIAccessToken") {
// Specify the URL string that we'll get the profile info from.
let targetURLString = "https://api.linkedin.com/v1/people/~/shares"
let payloadStr: String = "{"comment":"Check out developer.linkedin.com!","visibility":{"code":"anyone"}}"
// Initialize a mutable URL request object.
let request = NSMutableURLRequest(url: NSURL(string: targetURLString)! as URL)
// Indicate that this is a GET request.
request.httpMethod = "POST"
request.httpBody = payloadStr.data(using: String.Encoding.utf8)
// Add the access token as an HTTP header field.
request.addValue("Bearer (accessToken)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("json", forHTTPHeaderField: "x-li-format")
// Make the request.
let task: URLSessionDataTask = URLSession.shared.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 == 201 {
// Convert the received JSON data into a dictionary.
guard ((try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any]) != nil else {
print("Not containing JSON")
return
}
print("successfully posted.")
}
}
task.resume()
}

最新更新