invalid value around character 1 - swift3.2

trying to send data to server but every time i run my code an empty row is added to the database and an error appears in xcode as : "Invalid value around character 1." UserInfo={NSDebugDescription=Invalid value around character 1.}
#IBAction func submitButton(_ sender: Any) {
let parameters = ["paramname": "abc",
"paramemail": "hammadnaeem680#gmail.com",
"parammobile": "1234567890",
"paramroomno": "402",
"paramtime": "9",
"paramsno": "137865",
"paramcomplaint": "ios appp check",
"paramblock": "CSE",
"paramtype": "server"] as Dictionary< String, String>
guard let url=URL(string:"http://uietcloud.puchd.ac.in/mail/submit.php")
else {
return
}
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Value", forHTTPHeaderField: "Key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else {
return}
request.httpBody = httpBody
request.addValue("application/json", forHTTPHeaderField: "Accept")
session.dataTask(with: request) { (data, response, error) in
if let data = data
{
do
{
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
print(json)
print("not an error")
}
catch{
print(error)
print("this is an error")
}
}
}
.resume()
}

Try turning off prettyPrinted option when serializing to JSON. Your server likely wants it ugly. :)

Related

How to use json response as parameter in another api post call?

I make a GET call and receive a json response. I need to use that json response as one parameter for a subsequent POST call.
I’ve tried to:
-parse the data into an object and pass the [object] as parameter
-parse the data into a string and pass the string as parameter
-parse the data as dict and pass the dict as parameter
but it’s not working, I believe it’s a data thing or a secret I’m missing
How do you use a json response as parameter for a subsequent api call?
//MARK: - PIXLAB facedetect
func facedetectGET(uploadedUrl: String) {
var urlComponents = URLComponents(string: "https://api.pixlab.io/facedetect")
urlComponents?.queryItems = [
URLQueryItem(name: "img", value: uploadedUrl),
URLQueryItem(name: "key", value: Constants.pixlabAPIkey),
]
let url = urlComponents?.url
if let url = url {
// Create URL Request
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10.0)
request.httpMethod = "GET"
request.addValue("Bearer \(Constants.pixlabAPIkey)", forHTTPHeaderField: "Authorization")
// Get URLSession
let session = URLSession.shared
// Create Data Task
let dataTask = session.dataTask(with: request) { (data, response, error) in
// Check that there isn't an error
if error == nil {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
//make a dict
//let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any]
print("SUCCESS: image detected")
print(json)
//make json a string utf8 so it can be used as parameter in next call
//let jsonString = String(data: json as! Data, encoding: .utf8)
//let jsonData = json.data(using: .utf8)!
//parse json
//decode the json to an array of faces
let faces: [Face] = try! JSONDecoder().decode([Face].self, from: data!)
let facesString = String(faces)
//use dispatch main sync queue??"bottom": Int,
//mogrify call
mogrify(uploadedUrl: uploadedUrl, cord: faces)
}
catch {
print(error)
}
}
}
// Start the Data Task
dataTask.resume()
}
}
//MOGRIFY CALL
func mogrify(uploadedUrl: String, cord: Any) {
let mogrifyurl = URL(string: "https://api.pixlab.io/mogrify")!
//let param: [Face] = result.faces
let param: [String: Any] = ["img": uploadedUrl, "cord": cord]
var request = URLRequest(url: mogrifyurl)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(Constants.pixlabAPIkey)", forHTTPHeaderField: "Authorization")
request.httpMethod = "POST"
request.httpBody = try! JSONSerialization.data(withJSONObject: param, options: [])
URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print(error!)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!)
print(json)
} catch {
print("error")
}
}.resume()
}
this is how pretty the response looks
enter image description here
and this is how it looks when I pass it as parameter
enter image description here
A POST needs the body as Data. If you're just forwarding the body of the GET to the body of the POST, it would be easiest to leave it as Data.
You could also deserialize the response into an object in your get, and then re-serialize it back into Data in the POST code, but why?
I did lots of white magic, voodoo and lots of praying (aka try and error) and I made it work…
basically decoded the json data, then got an array subdata and encode it back into a data variable as input for the post call
maybe there is an easier and more elegant way but this works....
do {
//decode the json to an array of faces
let cord = try! JSONDecoder().decode(Cord.self, from: data!)
print(cord.faces)
let cordData = try! JSONEncoder().encode(cord.faces)
let coordinates = try JSONSerialization.jsonObject(with: cordData, options: [])
print(coordinates)
//mogrify call
mogrify(uploadedUrl: uploadedUrl, cord: coordinates)
} catch {
print(error)
}
post call
//MOGRIFY CALL
func mogrify(uploadedUrl: String, cord: Any) {
let mogrifyurl = URL(string: "https://api.pixlab.io/mogrify")!
// let param: [Face] = result.faces
let param: [String: Any] = ["img": uploadedUrl, "key": Constants.pixlabAPIkey, "cord": cord]
var request = URLRequest(url: mogrifyurl)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(Constants.pixlabAPIkey)", forHTTPHeaderField: "Authorization")
request.httpMethod = "POST"
request.httpBody = try! JSONSerialization.data(withJSONObject: param, options: [])
URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print(error!)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!)
print("MOGRIFY response")
print(json)
} catch {
print("error")
}
}.resume()
}

URL Session Post with form-data parameter in iOS Swift

I am trying to POST a parameter using form-data in swift.
I want to pass a mobile number with url session in form-data format. but I can't able to send data properly . please help me to pass data on form-data format in url session.
code I have Tried:
func registerService(){
print("register tapped")
let parameters: [String: Any] = [
"mobile" : mobileNumber
]
let url = URL(string: "http://54.251.198.30/api/user/login")
var req = URLRequest(url: url!)
req.httpMethod = "POST"
let boundary = "Boundary-\(UUID().uuidString)"
req.addValue("multipart/form-data : \(boundary)", forHTTPHeaderField: "Contet-Type")
req.addValue("multipart/form-data", forHTTPHeaderField: "Accept")
req.httpBody = NSKeyedArchiver.archivedData(withRootObject: parameters)
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else {return}
req.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: req, completionHandler: {(data, response, error) in
if response != nil {
print(response)
}
if let jsonResponse = try? JSONDecoder().decode(LoginBase.self, from: data!) {
print(jsonResponse)
}else{
print("error")
}
}).resume()
}
I have added an image which parameter I want to pass. you Can see Here
thanks for your response
I have modified your function parameter as well as request-body in the correct syntax. Now you can use as follows:-
func Register(){
print("register tapped")
let parameters: [String: Any] = ["mobile" : mobileNumber] as Dictionary<String, Any>
var request = URLRequest(url: URL(string: "http://54.251.198.30/api/user/login")!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
print(response!)
do {
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
print(json)
} catch {
print("error")
}
})
task.resume()
}

how to send a string in body with rawdata in swift 4 without alamofire?

{
"1":[{"name":"some product","type":"simple","quantity":"2","price":"500"}],
"2":[{"name":"Seller 2 add no 2","type":"feature","quantity":"1","price":"500"}],
"is_free_quota":"0",
"quotationIsVerified":"0"
}
this is the string which I have to send
//in this function we are sending token for authentication and data is sending in the raw data form body... with out parameteres and without alamofire
func postRequest() -> Void) {
let parameters = [""]
let url = URL(string: "http://192.168.10.7/retbajri/public/api/request/quot")!
print(url)
let user1 = ["name_or any string data which you want to post"]
let data : Data = user1.data(using: .utf8)!
//create the session object
let session = URLSession.shared
//now create the Request 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: parameters, options: .prettyPrinted) // pass dictionary to data object and set it as request body
} catch let error {
print(error.localizedDescription)
completion(nil, error)
}
//HTTP Headers
request.setValue("Bearer \(ttkknn)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue(NSLocalizedString("lang", comment: ""), forHTTPHeaderField:"Accept-Language");
request.httpBody = data
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request, completionHandler: { data, response, error in
guard error == nil else {
completion(nil, error)
return
}
guard let data = data else {
completion(nil, NSError(domain: "dataNilError", code: -100001, userInfo: nil))
return
}
do {
//create json object from data
guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else {
completion(nil, NSError(domain: "invalidJSONTypeError", code: -100009, userInfo: nil))
return
}
print(json)
} catch let error {
print(error.localizedDescription)
completion(nil, error)
}
})
task.resume()
}

Swift parsing a http request returns domain error

okay, so Im trying to make a post request but when I try to parse the data, I always get a error domain code= 3840.
https://www.codepunker.com/tools/http-requests/64243-brrjq9t
In this example it shows what the request response looks like.
and this is my code:
let parameters = ["txt": "כאב גרון","usr": "","pass": "" ,"ktivmale": false] as [String : Any]
guard let url = URL(string: "http://www.nakdan.com/GetResult.aspx") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
request.httpBody = httpBody
let task = URLSession.shared.dataTask(with: request as URLRequest){
data,response, error in
print(response!)
if error != nil{
print("error")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
DispatchQueue.main.async(execute: { () -> Void in
print(json)
SVProgressHUD.dismiss()
})
} catch {
print(error)
SVProgressHUD.dismiss()
SVProgressHUD.showError(withStatus: "Connection Failed.")
}
}
task.resume()

POST request not being sent in Swift

I would just like to ask. Why is my POST request below not being sent? The code seems perfectly sound, and Xcode shows no errors. I am using Swift 3. Could you please help me? Thanks! My code is below, my post URL is here. Thanks again!
#IBAction func onClick(_ sender: Any) {
let username = Username.text
let password = Password.text
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
let params = ["username": username, "password": password] as Dictionary<String, AnyObject>
do {
try request.httpBody = JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
} catch {
print("Error")
}
request.addValue("application/JSON", forHTTPHeaderField: "Content-Type")
URLSession.shared.getAllTasks { (openTasks: [URLSessionTask]) in
NSLog("open tasks: \(openTasks)")
}
}
You need to use:
let task = session.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) in
// do stuff with response, data & error here
print(error)
print(response)
})
task.resume()
Get more info here
You have to use URLSession.shared.dataTask(with:completionHandler:). Also, don't use NSMutableRequest, but use the native Swift version, URLRequest.
#IBAction func onClick(_ sender: Any) {
let username = Username.text
let password = Password.text
var request = URLRequest(url: url)
request.httpMethod = "POST"
let params = ["username": username, "password": password] as Dictionary<String, AnyObject>
do {
try request.httpBody = JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
} catch {
print("Error")
}
request.addValue("application/JSON", forHTTPHeaderField: "Content-Type")
URLSession.shared.dataTask(with: request, completionHandler: { data,response, error in
if let existingError = error {
//handle error
}
//handle response and/or data
}).resume()
}