Passing an array of parameters as a request body in swift - ios

I'm trying to pass an array of parameters that looks like this:
{
"watermarks": [
{
"email" : "correo_user",
"event_type" : "app",
"watermark" : "marcaAgua",
"date" : "date",
"location" : "location",
"segment" : 1,
"time" : "time",
"country" : "country",
"city" : "city"
}
]
}
I don't know how to pass it as an array of objects because I have never done it before. This is the code that I'm currently using:
func marcaAgua(parameters: [String: Any],
completion: #escaping (Result<[MarcaAguaResData], Error>)-> Void) {
let urlString = baseUrl + "events"
guard let url = URL(string: urlString) else {
completion(.failure(NetworkingError.badUrl))
return
}
var request = URLRequest(url: url)
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
request.httpMethod = "POST"
request.setValue("Bearer \(token_login)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
guard let unwrappedResponse = response as? HTTPURLResponse else {
completion(.failure(NetworkingError.badResponse))
return
}
switch unwrappedResponse.statusCode {
case 200 ..< 300:
print("success")
default:
print("failure")
}
if let unwrappedError = error {
completion(.failure(unwrappedError))
return
}
if let unwrappedData = data {
print("QQQQQ")
print(unwrappedData)
do{
let json = try JSONSerialization.jsonObject(with: unwrappedData, options:.allowFragments)
if let successRes = try? JSONDecoder().decode([MarcaAguaResData].self, from: unwrappedData){
completion(.success(successRes))
}else{
let errorResponse = try JSONDecoder().decode([MarcaAguaErrorResponse].self, from: unwrappedData)
print("Error \(errorResponse)")
completion(.failure(errorResponse as! Error))
}
}catch{
print("AAA")
completion(.failure(error))
}
}
}
}
task.resume()
}
When I pass the parameters to the function when I call it, I pass them as a dictionary of type [String:Any]. This is an example of it:
let signupQueryData : [String : Any] = [
"watermarks": [
"email" : correo_user as String,
"event_type" : "app" as String,
"watermark" : marcaAgua as String,
"date" : "\(dateActual) \(hour):\(minutes)" as String,
"location" : latitudYLongitud as String,
"segment" : 1 as Int,
"time" : "\(hour):\(minutes)" as String,
"country" : "\(qlq)" as String,
"city" : "Caracas" as String
]
]
And this is what it prints of parameters in the function marcaAgua:
["watermarks": ["time": "22:10", "segment": 1, "location": "location", "email": "mail", "event_type": "app", "watermark": "e356eaadcb3aa4a1049441fc48d83a22", "date": "13.07.2021 22:10", "country": "Venezuela", "city": "Caracas"]]
When I do that, I get the following error:
failure(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})

Try do like this
func marcaAgua(parameters: [String: Any],
completion: #escaping (Result<[MarcaAguaResData], Error>)-> Void) {
let urlString = baseUrl + "events"
guard let url = URL(string: urlString) else {
completion(.failure(NetworkingError.badUrl))
return
}
var request = URLRequest(url: url)
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
request.httpMethod = "POST"
request.setValue("Bearer \(token_login)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
guard let unwrappedResponse = response as? HTTPURLResponse else {
completion(.failure(NetworkingError.badResponse))
return
}
switch unwrappedResponse.statusCode {
case 200 ..< 300:
print("success")
default:
print("failure")
}
if let unwrappedError = error {
completion(.failure(unwrappedError))
return
}
if let unwrappedData = data {
do{
let json = try JSONSerialization.jsonObject(with: unwrappedData, options:.allowFragments)
if let successRes = try? JSONDecoder().decode([MarcaAguaResData].self, from: unwrappedData){
completion(.success(successRes))
}else{
let errorResponse = try JSONDecoder().decode([MarcaAguaErrorResponse].self, from: unwrappedData)
completion(.failure(errorResponse as! Error))
}
}catch{
completion(.failure(error))
}
}
}
}
task.resume()
}

initialise Variables
var invitationsArray = Array<[String: Any]>()
var invitations = Array<[String: Any]>()
Logic
invitations = [["friend_id": "\(each.friendId!)", "invited_type": "friend"]]
invitationsArray.append(contentsOf: invitations)
Set variables
let params: [String: Any] = [
"user_id":Global.shared.currentUserLogin.id,
"ride_name": planARide.name!,
"ride_description": planARide.description!,
"ride_type": planARide.rideType!,
"ride_date_and_time": planARide.rideDate!,
"ride_city": planARide.city!,
"ride_meeting_spot": planARide.rideMeetingSpot!,
"ride_meeting_latitude": planARide.latitude!,
"ride_meeting_longitude": planARide.longitude!,
"ride_intensity": planARide.rideIntensity!,
"time_length_of_ride": planARide.rideTime!,
"reoccuring_ride": planARide.rideReccurring!,
"special_instructions": planARide.specialInstruction!,
"open_ride_to_biking_community": planARide.openRideToBikingCommunity!,
"invitations": invitationsArray
]

Related

Problem parsing JSON data from server Swift

I'm trying to parse data from the server, but I get this error:
failure(Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil)))
The parameters should be passed as an array of objects, as well as the response object. I can't figure out what should I change in my code so the response is well structured.
This is what a response looks like:
[
{
'code' : number,
'error' => boolean,
'code_error' => number,
'data_error' => string,
'message' => 'Falta Campo requerido'
}
]
These are the parameters that should be passed:
[
{
'email' => 'required|string|email',
'event_type' => 'required|string',
'watermark' => 'required|string',
'date' => 'required',
'location' => 'required|string',
'segment' => 'required',
'time' => 'required',
'country' => 'required',
'city' => 'required'
}
]
And this is what my code looks like.
Data:
struct MarcaAguaResData: Codable {
let code: Int
let error: Bool
let message: String
}
struct MarcaAguaErrorResponse: Decodable, LocalizedError {
let code: Int
let error: Bool
let message: String
let code_error: Int
let data_error: String
}
Server:
class MarcaAguaService {
func marcaAgua(parameters: [String: Any],
completion: #escaping (Result<MarcaAguaResData, Error>)-> Void) {
let urlString = baseUrl + "events"
guard let url = URL(string: urlString) else {
completion(.failure(NetworkingError.badUrl))
return
}
var request = URLRequest(url: url)
var components = URLComponents()
var queryItems = [URLQueryItem]()
for (key, value) in parameters {
let queryItem = URLQueryItem(name: key, value: String(describing: value))
queryItems.append(queryItem)
}
components.queryItems = queryItems
let queryItemsData = components.query?.data(using: .utf8)
request.httpBody = queryItemsData
request.httpMethod = "POST"
request.setValue("Bearer \(token_login)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
guard let unwrappedResponse = response as? HTTPURLResponse else {
completion(.failure(NetworkingError.badResponse))
return
}
switch unwrappedResponse.statusCode {
case 200 ..< 300:
print("success")
default:
print("failure")
}
if let unwrappedError = error {
completion(.failure(unwrappedError))
return
}
if let unwrappedData = data {
do{
let json = try JSONSerialization.jsonObject(with: unwrappedData, options: .allowFragments)
print("BBBB")
print(json)
if let successRes = try? JSONDecoder().decode(MarcaAguaResData.self, from: unwrappedData){
completion(.success(successRes))
}else{
let errorResponse = try JSONDecoder().decode(MarcaAguaErrorResponse.self, from: unwrappedData)
print("Error \(errorResponse)")
completion(.failure(errorResponse))
}
}catch{
print("AAA")
completion(.failure(error))
}
}
}
}
task.resume()
}
}
To be [MarcaAguaResData].self which is an array instead of MarcaAguaResData.self which is a dictionary
if let successRes = try? JSONDecoder().decode([MarcaAguaResData].self, from: unwrappedData){
completion(.success(successRes))
}else{
let errorResponse = try JSONDecoder().decode([MarcaAguaErrorResponse].self, from: unwrappedData)
print("Error \(errorResponse)")
completion(.failure(errorResponse))
}
With
completion: #escaping (Result<[MarcaAguaResData], Error>)-> Void)

Not able to get success in api response

This is how I am making an api request using URLSession:
let url = URL(string: "http://192.168.1.21.2/FeatureRequestComponent/FeatureRequestComponentAPI")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let parameters: [String: Any] = [
"AppID": "67B10F42-A372-4D4B-B630-5933E3F7FD65",
"FeatureTitle": "ABCD",
"UserName": "Ayaz",
"UserEmail": self.userEmailTextfield.text ?? "",
"Priority":"H",
"Description": self.featureDescriptionTextView.text ?? "",
"UseCase": self.useCaseTextView.text ?? "",
"DeviceType" : "iPhone"
]
request.httpBody = parameters.percentEscaped().data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data,
let response = response as? HTTPURLResponse,
error == nil else { // check for fundamental networking error
print("error", error ?? "Unknown error")
return
}
guard (200 ... 299) ~= response.statusCode else { // check for http errors
print("statusCode should be 2xx, but is \(response.statusCode)")
print("response = \(response)")
return
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
}
extension Dictionary {
func percentEscaped() -> String {
return map { (key, value) in
let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
return escapedKey + "=" + escapedValue
}
.joined(separator: "&")
}
}
extension CharacterSet {
static let urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]#" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowed
}()
}
above I have given the extensions for percent escaped and a character set also
But the response I get is an error like this:
responseString = Optional("{\"isError\":true,\"ErrorMessage\":\"Unknown Error Occured\",\"Result\":{},\"ErrorCode\":999}")
What am I doing wrong here...? I'm supposed to get a success in my response but what I'm getting is the error message.
I tried to detect the problem in your code but I did not find it
use my code war it works well
I hope this helps you
let jsonData = try? JSONSerialization.data(withJSONObject: ["username":username,"password":password])
var request = URLRequest(url: URL(string: "http://api.com/login")!)
request.httpMethod = "POST";
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
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 dataJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = dataJSON as? [String: Any] {
DispatchQueue.main.async {
let User = responseJSON["user"] as! [String:Any]
print("user: ", User)
print("name: ", User["name"]!)
print("email: ", User["email"]!)
}
}else {
print("error")
}
}
task.resume()

Text Detection problems with Google Vision

Not sure what the issues is as my code just stopped working overnight, but the text detection on Google Vision is either returning nil or returning words that are non-existent on the subject.
Here's my request function:
func createRequest(with imageBase64: String) {
let jsonRequest = [
"requests": [
"image": [
"content": imageBase64 ],
"features": [
["type": "TEXT_DETECTION"],
["type": "IMAGE_PROPERTIES"]
]
]
]
let jsonData = try? JSONSerialization.data(withJSONObject: jsonRequest)
var request = URLRequest(url: googleURL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(Bundle.main.bundleIdentifier ?? "", forHTTPHeaderField: "X-Ios-Bundle-Identifier")
request.httpBody = jsonData
DispatchQueue.global().async {
let task: URLSessionDataTask = self.URLsession.dataTask(with: request) { (encodedObject, response, error) in
guard let data = encodedObject, error == nil else {
print(error?.localizedDescription ?? "no data")
return
}
self.analyzeResults(data)
}
task.resume()
}
}
Part of my analyze results function:
func analyzeResults(_ data: Data) {
DispatchQueue.main.async {
guard let response = try? JSONDecoder().decode(Root.self, from: data) else { return }
guard let responseArray = response.responses else { return }
print(response)

How to avoid "Error Domain=NSCocoaErrorDomain Code=3840" in Swift?

I keep getting this particular error when trying to parse a JSON response in Swift:
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
Code:
let dict = [
"phone": phone,
"firstname": "\(String(describing: firstName))",
"lastname": "\(String(describing: lastName))"
]
as [String: Any]
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) {
var request = URLRequest(url: URL(string: "\(config.baseURL)employee")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
request.timeoutInterval = 30.0
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if error != nil {
DispatchQueue.main.async {
self.alertController.singleButtonAlertController("Error", (error?.localizedDescription)!, self, self.defaultAction)
return
}
}
guard let data_ = data else {
return
}
do {
let jsonObj = try JSONSerialization.jsonObject(with: data_, options: .mutableContainers) as? NSDictionary
guard let parseJSON = jsonObj else {
return
}
self.navigationItem.rightBarButtonItem = self.rightBarButton
let meta = parseJSON["meta"] as? [String:Any]
let status = meta!["status"] as? String
if status == "200" {
isEmployeeModified = true
self.dismiss(animated: true, completion: nil)
} else {
let info = meta!["info"] as? String
let message = meta!["message"] as? String
DispatchQueue.main.async {
self.alertController.singleButtonAlertController(info!, message!, self, self.defaultAction)
}
}
} catch let error as NSError {
print(error)
}
}
task.resume()
I have used similar codes in other parts of the project and everything checks out.
According to this Error, the response from your server is not a valid JSON
Can you use responseString instead of responseJSON like below
Alamofire.request(URL, method: requestMethod, parameters: params).responseString{ response in
print(response)
}
I was able to figure out what was wrong and I'm going to explain this here for future readers. Apparently, I was doing a GET request the wrong way, so when I intend to do a POST request, for some reason, it still sees it as a GET request and that was why I kept getting the response: Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
Below is my refactored code and it works without any hassle:
let dict = [
"phone": phone,
"firstname": firstName,
"lastname": lastName
] as [String : Any]
guard let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) else {
return
}
guard let url = URL(string: "\(config.baseURL)employee") else {
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData as Data
request.timeoutInterval = 10
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print("JSON Response: \(response)")
}
if error != nil {
DispatchQueue.main.async {
self.navigationItem.rightBarButtonItem = self.rightBarButton
self.alertController.singleButtonAlertController("Error", (error?.localizedDescription)!, self, self.defaultAction)
return
}
}
if let data = data {
do {
let parseJSON = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary
let meta = parseJSON!["meta"] as? [String:Any]
let status = meta!["status"] as? String
if status == "200" {
isEmployeeModified = true
self.dismiss(animated: true, completion: nil)
} else {
let info = meta!["info"] as? String
let message = meta!["message"] as? String
DispatchQueue.main.async {
self.alertController.singleButtonAlertController(info!, message!, self, self.defaultAction)
}
}
} catch {
print(error)
}
}
}.resume()

How to send json as parameter iOS swift?

I want to send following object as body parameter. But serialization is failing:
{
"StartAddress":"Colombo",
"EndAddress":"Kandy",
"DepartureAddress":"Kollupitiya, Colombo",
"ArrivalAddress":"Peradeniya, Kandy",
"CreatedDate":"2017-07-30",
"Date":"2017-07-30",
"Time":"2017-07-30",
"IsLadiesOnly":true,
"IpAddress":"fe80::8638:38ff:fec8:ea50%wlan0",
"Country":"Srilanka",
"VehicleId":"1129",
"StartLocation":[
6.9270974,
79.8607731
],
"EndLocation":[
7.2916216,
80.6341326
],
"Points":"k}gi#y{lf",
"Route":{
"Bounds":{
"NorthEast":[
7.2916216,
80.6341326
],
"SouthWest":[
6.9270974,
79.8607731
]
},
"Legs":[
{
"LegId":1,
"Distance":14904,
"Duration":1941,
"StartAddress":"Colombo",
"EndAddress":"Kadawatha",
"StartLocation":[
6.9270974,
79.8612478
],
"EndLocation":[
7.0011125,
79.95000750000001
],
"Ancestors":[
],
"Price":745
},
{
"LegId":2,
"Distance":63040,
"Duration":6209,
"StartAddress":"Kadawatha",
"EndAddress":"Kegalle",
"StartLocation":[
7.0011125,
79.95000750000001
],
"EndLocation":[
7.251436200000001,
80.3466076
],
"Ancestors":[
"Colombo"
],
"Price":3152
},
{
"LegId":3,
"Distance":38990,
"Duration":4430,
"StartAddress":"Kegalle",
"EndAddress":"Kandy",
"StartLocation":[
7.251436200000001,
80.3466076
],
"EndLocation":[
7.2901864,
80.6338425
],
"Ancestors":[
"Colombo",
"Kadawatha"
],
"Price":1950
}
]
},
"TotalPrice":"5847.0",
"SeatCount":1,
"Detour":1,
"Luggage":2,
"DetoursDescription":"10 Minutes",
"LuggageDescription":"Small Luggage",
"Notes":"new ride"
}
when I try to serialize it before send it gives an error:
'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization
dataWithJSONObject:options:error:]: Invalid top-level type in JSON
write'
func synchronusPostRequstWithHeadersJson(apiMethod:String, params:JSON, headers:[ String: String]) -> ResultModel {
let resultModel = ResultModel()
//create the url with URL
let url = URL(string: BASE_URL + apiMethod )!
let session = URLSession.shared
//// **** HERE IT FAILING *****////
let jsonData = try? JSONSerialization.data(withJSONObject: params)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData
for item in headers {
request.addValue(item.value, forHTTPHeaderField: item.key)
}
let semaphore = DispatchSemaphore(value: 0)
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
if(error != nil){
resultModel.ErrorType = .NO_INT
resultModel.JsonReslut = JSON.null
}else{
if let resp = response as? HTTPURLResponse{
if(resp.statusCode == 200){
if let jsonResult = JSON(data) as? JSON {
resultModel.ErrorType = .NO_ERROR
resultModel.JsonReslut = jsonResult
}
}else{
if let jsonResult = JSON(data) as? JSON {
resultModel.ErrorType = .SEREVR_ERROR
resultModel.JsonReslut = jsonResult
}else{
resultModel.ErrorType = .SEREVR_ERROR
resultModel.JsonReslut = JSON.null
}
}
}
}
semaphore.signal()
})
task.resume()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
return resultModel
}
How can i send that request?. Is it possible with alamofire?
Using Almofire you can achieve this as
let params: [String: Any] = [
"StartAddress":"Colombo",
"EndAddress":"Kandy",
"DepartureAddress":"Kollupitiya, Colombo",
"StartLocation":[
6.9270974,
79.8607731
],
"EndLocation":[
7.2916216,
80.6341326
],
] //Do check your dictionary it must be in correct format
Alamofire.request("yourUrl", method: .post, parameters: params, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
}
try using:
let session = Foundation.URLSession.shared
let url = URL(string: "Your server url")
var request = URLRequest(url : url!)
request.httpMethod = "POST"
let params :[String:Any] = ["name":"yuyutsu" as Any,"rollno":12 as Any] //Add your params
do {
let jsonData = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
session.dataTask(with: request, completionHandler: { data, response, error in
OperationQueue.main.addOperation {
guard error == nil && data != nil else { // check for fundamental networking error
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
// print("response = \(response)")
}
let responseString = String(data: data!, encoding: String.Encoding.utf8)
print("responseString = \(responseString!)")
if let responsedata = responseString!.data(using: String.Encoding.utf8)! as? Data{
do {
let jsonResult:NSDictionary = try JSONSerialization.jsonObject(with: responsedata, options: []) as! NSDictionary
print("Get The Result \(jsonResult)")
if error != nil {
// print("error=\(error)")
}
if let str = jsonResult["success"] as? NSNull {
print("error=\(str)")
}
else {
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Response string : \(responseString)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
}) .resume()
}catch {
// print("Error -> \(error)")
}
hope this might help you out.
Creating JSON parameters to send it as a post body:
Function:
//MARK:- Create JSON String
func createJSONParameterString(postBody:AnyObject) -> String {
if let objectData = try? JSONSerialization.data(withJSONObject: postBody, options: JSONSerialization.WritingOptions(rawValue: 0)) {
let objectString = String(data: objectData, encoding: .utf8)
return objectString ?? ""
}
return ""
}
Usage:
var postBody = [AnyHashable:Any]()
postBody["device_id"] = "device_ID"
let parameters = createJSONParameterString(postBody: postBody as AnyObject)
print(parameters)
i have solved similar problem using Alamofire and SwiftyJson as follow
let call your object (data )
let json = JSON(data)
let Params :Dictionary = json.dictionaryObject!
and in Alamofire request
Alamofire.request(url, method: .post, parameters: Params , encoding: JSONEncoding.prettyPrinted, headers: nil)
//.validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result
{
case .failure(let error):
case .success(let value):
}
it need to replace this "{ }" with "[ ]"
and alamofire and swift json handle that issue
ex:
[
{
"firstName" : " " ,
"lastName" : " "
},
{
"firstName" : " " ,
"lastName" : " "
}
]
change it to
[
[
"firstName" : " " ,
"lastName" : " "
],
[
"firstName" : " " ,
"lastName" : " "
]
]

Resources