reza5630
reza5630

Reputation: 21

Sharing on LinkedIn using Swift (Without SDK)

Though I have seen many solutions that worked sharing on LinkedIn, but I couldn't find any without using LISDKAPIHelper.

Here is my scenario. I have my valid accessToken, which I have already used to retrieve info from user profile. Below is the steps I have been trying to post using that token. I have been receiving 'statusCode = 400'. May be I have done something wrong with requestURL.

Can anyone help me in this regard?

Here is my code....

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

    }

}

Upvotes: 0

Views: 695

Answers (1)

reza5630
reza5630

Reputation: 21

Atlast I found my solution that worked for me. The thing I have been doing wrong is making my request header. It worked for me.

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

    }

Upvotes: 1

Related Questions