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 = 401
linkedinHelper.authorizeSuccess({ [unowned self] (lsToken) -> Void in
self.writeConsoleLine("Login success lsToken: \(lsToken)")
print("\(lsToken.accessToken ?? "")")
let targetURLString = "https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=\(lsToken.accessToken ?? "")&format=json"
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 \(lsToken.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()
}, error: { [unowned self] (error) -> Void in
self.writeConsoleLine("Encounter error: \(error.localizedDescription)")
}, cancel: { [unowned self] () -> Void in
self.writeConsoleLine("User Cancelled!")
})
LinkedIn v1 API is no longer supported. You will need to use their v2 APIs: https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin?context=linkedin/consumer/context
Your target URL should use the ugcPosts endpoint:
POST https://api.linkedin.com/v2/ugcPosts
In addition to Christopher's point, I'm afraid Linkedin doesn't appear to be processing the queue of people waiting for access to v2 of the API - we requested access 5 months ago, nothing has changed. We were using v1 of the API for 2 years without any issues, then one day they switched us off with no method of getting transferred to the new API.
Related
I have an Authentication Manager that send SignIn and SignUp request. Code works good on simulator and fetch data from database but not working on device. On device It gives http 500 error. I check the textfields before sending the request and they seem fine.
Any suggestions to solve this issue ?
func performSignIn(email: String, password: String){
//1. Create URL
if let url = URL(string: Constants.signInURL){
var request = URLRequest(url: url)
//Request Body
var body = [String : Any]()
body["user"] = ["email": email,
"password": password]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: body, options: [])
} catch {
print("JSON serialization failed: \(error)")
}
// Change the URLRequest to a POST request
request.httpMethod = "POST"
//Need to tell that request has json in body.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//2. Create URLSession
let session = URLSession(configuration: .default)
//3. Give Session a task
let task = session.dataTask(with: request) { (data, response, error) in
if error != nil{
DispatchQueue.main.async {
delegate?.failedWithError(error: error!)
return
}
}
if let safeData = data{
if let signInResponse = parseJSON(safeData){
//Who has the delegate run signInSuccess method
delegate?.signInSuccess(signInResponse)
}
}
}
//4. Start Task
task.resume()
}
}
I'm trying to create a URL Request in Swift to send an HTTP POST request to a Discord Webhook, and the request completes in a failure defined as 'responseProblem'. I'm not sure where the response problem is originating from.
Discord should technically be able to accept HTTP requests, and a bunch of research into the issue has led me nowhere. I've worked with Discord webhooks before, but I've never played around with this kind of stuff before, so I'm kinda stuck for what I should do now.
import Foundation
enum APIError:Error {
case responseProblem
case decodingProblem
case encodingProblem
}
struct APIRequest {
let resourceURL: URL
init(endpoint: String) {
let resourceString = "<discord-webhook-url-removed-for-privacy>"
guard let resourceURL = URL(string: resourceString) else {fatalError()}
self.resourceURL = resourceURL
}
func save (_ messageToSave:Message, completion: #escaping(Result<Message, APIError>) -> Void ) {
do {
var urlRequest = URLRequest(url: resourceURL)
urlRequest.httpMethod = "POST"
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.httpBody = try JSONEncoder().encode(messageToSave)
let dataTask = URLSession.shared.dataTask(with: urlRequest) { data, response, _ in
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, let
jsonData = data else {
completion(.failure(.responseProblem)) // <<< 'responseProblem' is outputted in console as the error
return
}
do {
let messageData = try JSONDecoder().decode(Message.self, from: jsonData)
completion(.success(messageData))
} catch {
completion(.failure(.decodingProblem))
}
}
dataTask.resume()
} catch {
completion(.failure(.encodingProblem))
}
}
}
When I run this Swift program, I expected it to send a request to the Discord Webhook to send a message into it's designated channel. However, the only error outputted into the console is responseProblem. Please let me know if there is anything further I need to add to get the root cause of the problem (I'm still semi-fresh to Swift, and I normally work with JavaScript, so I'm not sure how to properly debug in Swift and Xcode.)
Swift app is built in iOS 12.2 because Xcode doesn't like this stuff in iOS 13
This is a simplified version of how I post to a Discord webhook with Swift. From your post I can't see how you're converting your custom Message struct into a JSON dictionary, but you need at least the key/value pair for "content" to successfully post a Discord Webhook. And of course the posts can be customized in many other ways (with a custom "username" etc.).
var messageString: String = ""
guard let url = URL(string: "your-full-discord-webhook-url") else { return }
let messageJson: [String: Any] = ["content": messageString]
let jsonData = try? JSONSerialization.data(withJSONObject: messageJson)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "content-type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request)
task.resume()
When I hit the api from simulator/device, it's taking almost 18-20 seconds to fetch data from api response, where as the same API is getting response in 1.4 seconds in POSTMAN Application. This issue is happening for almost all APIs. Even I have tried with Alamofire, but same issue is happening. How to resolve this issue? Thanks in advance!
I'm using below code in network manager class:
typealias serverResponseBlock = (_ success: Bool, _ message: String, _ dataDict: [AnyHashable: Any]) -> Void
class func createRequest(httpMethod : HTTPMethod, endPoint : String, parameters : [String : Any], completion: #escaping serverResponseBlock) -> Void {
let baseUrl = ApiConstants.kBaseUrl + ApiConstants.kPath + endPoint
var request = URLRequest.init(url: URL.init(string: baseUrl)!)
request.timeoutInterval = 60
request.httpMethod = httpMethod.rawValue
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
request.addValue("Bearer \(StoredValues.Token)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
if error == nil{
let httpResponse = response as! HTTPURLResponse
if httpResponse.statusCode == 200 {
do {
let json = try JSONSerialization.jsonObject(with: data!)
APIManager.processResponse(responseObject: json, block: completion)
} catch {
print("error")
}
}else{
completion(false, "Could not complete your request", [:])
}
}else{
completion(false, /error?.localizedDescription, [:])
}
})
task.resume()
}
Hi I want to integrate the Curl POST api in my code I don't have any idea about this could any please guide me how to integrate this in swift language
The below web service call I have integrate in my code, Have tried but didn't get the result
curl -X POST http://stf.rortechnologies.com/api/session.js --data '{"user": {"email":"XXXXXX", "password":"XXXXXX"}}' -H "Content-Type:application/json"
let parameters = ["email":"admin.test#stf.com", "password":"password"]
let header = ["user": parameters]
//create the url with URL
let url = URL(string: "http://stf.rortechnologies.com/api/session.js")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: header, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
here am getting the null response
App Transport Security (ATS)
You are calling a http url and not a https url. In production always https should be used. This is enforced by iOS.
For testing purposes one can declare exceptions in the info.plist, the documentation can be found here:
https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW33
JSON Encoding/Decoding
In Swift there is a convenient way to encode/decode JSON with JSONEncode/JSONDecoder. A simple solution might look like the one below.
Define Parameter Structs
struct Login: Encodable {
let user: User
}
struct User: Encodable {
let email: String
let password: String
}
Define Return Struct
struct Result: Decodable {
//add expected JSON fields here
}
Rest Call
private func makeRestCall() {
let login = Login(user: User(email: "admin.test#stf.com", password: "password"))
guard let loginJson = try? JSONEncoder().encode(login) else { return }
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
guard let url = URL(string: "<add some valid url here>") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = loginJson
let dataTask = session.dataTask(with: request) { (data, response, error) in
if let response = response as? HTTPURLResponse {
if response.statusCode == 200 {
guard let data = data else {
print ("call failed - no data returned")
return
}
guard let result = try? JSONDecoder().decode(Result.self, from: data) else {
print ("json decoding failed")
return
}
print ("call succesfully returned \(result)")
} else {
print ("call failed with status \(response.statusCode)")
}
} else {
print ("call failed: no http response")
}
}
dataTask.resume()
}
Check in a HTTPS Proxy
To make sure that you send the correct data, you could use a HTTPS proxy software. There it would look like this:
I want to access the magenta REST API in my iOS application.
Following is my code to access the API:
func getCustomerTokenusingURLSEssion(){
let url = URL(string: "HTTPURL")!
var urlRequest = URLRequest(
url: url,
cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 10.0 * 1000)
urlRequest.httpMethod = "POST"
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
let json1: [String: Any] = [
"username": "xyz#gmail.com",
"password":"xyz12345"]
let jsonData = try? JSONSerialization.data(withJSONObject: json1, options: .prettyPrinted)
urlRequest.httpBody = jsonData
let config = URLSessionConfiguration.default
let urlsession = URLSession(configuration: config)
let task = urlsession.dataTask(with: urlRequest){ (data, response, error) -> Void in
print("response from server: \(response)")
guard error == nil else {
print("Error while fetching remote rooms: \(error)")
return
}
guard let data = data,
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
print("Nil data received from fetchAllRooms service ")
return
}
print("JSON \(json)")
}
task.resume()
}
But I'm getting error message form the server as follow:
["message": Server cannot understand Content-Type HTTP header media type application/x-www-form-urlencoded]
Please help!
Thanks!
Here's working example of token-based authentication from iOS to magento2 using swift:
func restApiAuthorize(completionBlock: #escaping (String) -> Void) {
// Prepare json data
let json: [String: Any] = ["username": “yourusername”,
"password": “yourpassowrd”]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
// Create post request
let url = URL(string: "http://yourmagentodomain.com/index.php/rest/V1/integration/customer/token")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("\(jsonData!.count)", forHTTPHeaderField: "Content-Length")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// Insert json data to the request
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
// 1: Check HTTP Response for successful GET request
guard let httpResponse = response as? HTTPURLResponse
else {
print("error: not a valid http response")
return
}
print(httpResponse.statusCode)
switch (httpResponse.statusCode)
{
case 200:
let responseData = String(data: data, encoding: String.Encoding.utf8)!
print ("responseData: \(responseData)")
completionBlock(responseData)
default:
print("POST request got response \(httpResponse.statusCode)")
}
}
task.resume()
}
And usage is like that:
restApiAuthorize() { (output) in
// token data, I found it important to remove quotes otherwise token contains extra quotes in the end and beginning of string
let userToken = output.replacingOccurrences(of: "\"", with: "")
print ("userToken \(userToken)")
}
you can then write your userToken to userDefaults and make feature api calls.
Best Guest you forgot to set your Content-Type, so add this:
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")