sending parameters with json in swift - ios

I'm trying to use webapi in my code. my JSON service has odata filtering. But when I try to send my link into my JSON serializer, I get "nil" response at myURL2. But if I send without parameter it works fine. Do you have any suggestions? How can I use ODATA in my code?
let link = "https://apiservices.domain.com/api/Events?$filter=EventDate gt datetime'2018-02-01' and EventDate lt datetime'2018-02-15'"
let myURL2 = NSURL(string: link)
let request2 = NSMutableURLRequest(url: myURL2 as! URL)
request2.httpMethod = "GET"
request2.addValue("Bearer "+tokenNewId, forHTTPHeaderField: "Authorization")
request2.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
request2.setValue("application/json", forHTTPHeaderField: "Accept")
let task2 = URLSession.shared.dataTask(with: request2 as URLRequest) {(data2, response2, error2) -> Void in
if let unwrappedData2 = data2 {
do {
guard let records = try? JSONSerialization.jsonObject(with: unwrappedData2, options: .mutableContainers) as? [[String: Any]] else {
return
}
}

Try this:
let urlwithPercentEscapes = link.addingPercentEncoding(
withAllowedCharacters: .urlQueryAllowed)
let myURL2 = NSURL(string: urlwithPercentEscapes!)

I believe that your problem is that your url is not percent-encoded. You need to use the stringByAddingPercentEncodingWithAllowedCharacters: method to do that.
Here is a post that shows you how to do it.

Related

Send data to Airtables through a POST request with a json body

Im trying to send data to Airtables using its REST APIs based on the documentation. The part Im stuck is adding the parameters. It throws me an error saying "Invalid request: parameter validation failed. Check your request data".
The Curl according to the doc as bellow.
My partially done code as bellow.
let table_name = "Diet%20Plan"
let base_id = "appmrzybooFj9mFVF"
let token = "SomeID"
// prepare json data
let json: [String: String] = ["Food Type": "Minseee",
"Person Name": "Rabiit Con"]
// create the url with URL
let url = URL(string: "https://api.airtable.com/v0/\(base_id)/\(table_name)")! // change server url accordingly
let jsonData = try? JSONSerialization.data(withJSONObject: json)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue( "Bearer \(token)", forHTTPHeaderField: "Authorization")
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
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON) //Code after Successfull POST Request
}
}
task.resume()
}
From your code, request body seems to be made like:
{"Person Name":"Rabiit Con","Food Type":"Minseee"}
What it needs to be sending is:
"fields": {
"Person Name":"Rabiit Con",
"Food Type":"Minseee"
}
Try
let json: [String: Any] = ["fields": ["Food Type": "Minseee",
"Person Name": "Rabiit Con"]]
let jsonData = try? JSONSerialization.data(withJSONObject: json)

Siri Shortcut Intent API call says URL is nil, but its not

Here is the code that I am dealing with:
let url = "https://www.host.com/url/\(intent.cardInfo!)"
print(url)
let url2 = URL(string: url)! // this is nil??
let request = NSMutableURLRequest(url: url2)
Below is an image showing that this value is not nil (you can see that in the console). I get the value after the Siri intent. This is inside of the IntentHandler. All of the code is below.
class SoldForAppIntentHandler : NSObject, SoldForAppIntentHandling {
func handle(intent: SoldForAppIntent, completion: #escaping (SoldForAppIntentResponse) -> Void) {
print(intent.sport!)
print(intent.cardInfo!)
print(intent.cardNumber!)
let url = "https://www.host.com/url/\(intent.cardInfo!)"
print(url)
let url2 = URL(string: url)!
let request = NSMutableURLRequest(url: url2)
request.httpMethod = "GET"
let postString = ""
request.httpBody = postString.data(using: String.Encoding.utf8)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
//print(json!)
let response = json!["value"] as! String
} catch {
print(" error adding tap search to db:\(error)")
}
print()
}
task.resume()
completion(SoldForAppIntentResponse.success(response: "\n\nSold For will look up \(intent.sport!) \(intent.cardInfo!) \(intent.cardNumber!)"))
}
Problem is actually url2 itself, because the string https://www.host.com/url/1986 fleer 57 Michael Jordan PSA 10 cannot be properly converted into URL object.
You can try something like this:
if let url = "https://www.host.com/url/\(intent.cardInfo!)".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
let url2 = URL(string: url)!
}

How to add urlencoded parameter to httpBody in urlRequest

i have created one common class for alamofire request
i want to send parameters as aplication/x-www-form-urlencoded
how to add the parameters to my urlRequest
i have managed to add parameters as application/json to urlRequest using below code
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
i need something similar for aplication/x-www-form-urlencoded
here is my parameters
case .ewalletData :
return [K.APIParameterKey.token :"OP8JHOEOZ5KJW1X",K.APIParameterKey.fromMobile:"true",K.APIParameterKey.adminName:"binaryecom",K.APIParameterKey.limit:"100",K.APIParameterKey.offset:"0",K.APIParameterKey.userName:"OC6DGH"]
here is the code it works for me in swift 4:
let postString = "your parameter="+value+"&your parameter="+value
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request, completionHandler: completionHandle)
task.resume()
try this :
guard let request_url = URL(string: Url) else { return }
let parameterDictionary = ["your parameter" : value]
var request = URLRequest(url: request_url)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
request.setValue("aplication/x-www-form-urlencoded", forHTTPHeaderField: "String")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
return
}
request.httpBody = httpBody

Getting an Authentication Failed error from server after hitting web service in Swift

The following below code is of hitting web service in swift by using NSURLSession .. I always get authentication failed message from server.Not able to get what is missing in request body.
let urlString:String = "\(BaseURL)"+"user_register.php?"
let deviceStr = "xyz"
let dictParam:NSDictionary = ["email":"\((emailTF?.text!)!)","username":"\((usernameTF?.text!)!)","password":"\((passwordTF?.text!)!)","device_key":deviceStr]
print(dictParam)
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request.timeoutInterval = 60.0
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
// request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPMethod = "POST"
let dataToPost = try! NSJSONSerialization.dataWithJSONObject(dictParam, options: [])
request.HTTPBody = dataToPost
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error")
return
}
let response:AnyObject! = try! NSJSONSerialization.JSONObjectWithData(data!, options: [])
print(data!)
print(response)
}
task.resume()

How to upload and associate an Image with a User in Parse.com (REST API), using Swift 2.0

I am trying to associate an image or a file with an object in Parse.com using the REST API. The Parse.com REST API Doc is quite vague, it talks about first how to upload which is fine, and then how to associate. The only issue is that it doesn't show how to associate with a User table, only an Object table, so when I tried to associate with a user, it asked for a username and password, and the response is as if it tries to create a new user. When I tried to associate with a regular table Company, it create a new entry. Any help would welcome, this is the code I have so far.
This is the code to upload a file to Parse.com with REST
let baseURL = NSURL(string: self.baseURL)
let url = NSURL(string: "/1/files/pic.jpg", relativeToURL: baseURL)
let request = NSMutableURLRequest()
request.HTTPMethod = "\(HTTPMethod.POST)"
request.addValue(appID, forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue(apiKey, forHTTPHeaderField: "X-Parse-REST-API-Key")
request.addValue("image/jpeg", forHTTPHeaderField: "Content-Type")
let image = UIImage(named: "empAvatar")
let imageData = UIImageJPEGRepresentation(image!, 0.9)
let base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let param = ["userProfile":base64String]
do{
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(param, options: .PrettyPrinted)
} catch {
print("ERROR: HTTP Body JSON")
}
request.URL = url
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
data, response, error in
do {
let imageDic = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject]
print("DATA: \(imageDic)")
} catch {
}
}
task.resume()
This is the code to associate a file with a user/object
let baseURL = NSURL(string: self.baseURL)
let url = NSURL(string: "/1/users/", relativeToURL: baseURL)
let request = NSMutableURLRequest()
request.HTTPMethod = "\(HTTPMethod.POST)"
request.addValue(appID, forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue(apiKey, forHTTPHeaderField: "X-Parse-REST-API-Key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let param = ["name":"John", "picture":["name":"tfss-127e50c4-be6e-4228-b1a3-3f253358ac-pic.jpg","__type":"File"]]
do{
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(param, options: .PrettyPrinted)
} catch {
print("ERROR: HTTP Body JSON")
}
request.URL = url
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
data, response, error in
do {
let imageDic = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject]
print("DATA: \(imageDic)")
} catch {
}
}
task.resume()
With the URL, I also tried:
let url = NSURL(string: "/1/class/Company/", relativeToURL: baseURL)
And it just created a new entry.
Thanks you!
POST request will create new entry try using PUT method instead.

Resources