Alamofire .post api error: Code=3840 "Invalid value around character 1 - ios

Using Alamofire for .post api, api giving data in postman but not in my code. Posting below the code, please guide what wrong i am doing here:
// API calling method:
parameters = [
"Address" : "" as AnyObject,
"Name" : "" as AnyObject,
"ServiceID" : "" as AnyObject,
"Rating" : "" as AnyObject,
"Price" : "" as AnyObject
]
let headers: Dictionary = [
"" : ""
]
print(parameters)
ApiServices.requestPOSTURL(strURL, params: parameters, headers: headers, success:{
(JSONResponse) -> Void in
CommonMethodsClass.hideHUD(targetView: self.view)
print(JSONResponse["message"])
let strMsg = JSONResponse["message"].stringValue
if (JSONResponse["status"].intValue == 1)
{
}
else
{
CommonMethodsClass.showAlertMessage(vc: self, titleStr: "Error!", messageStr: strMsg)
}
}) {
(error) -> Void in
print(error)
CommonMethodsClass.hideHUD(targetView: self.view)
}
// Api request method:
class func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, headers : [String : String]?, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void){
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default).responseJSON { (responseObject) -> Void in
print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value as Any)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
Error: FAILURE:
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
1." UserInfo={NSDebugDescription=Invalid value around character 1.}))
Update: Response to parse, may also needs to be changed.
{
"status": true,
"message": "",
"data": [
{
"SalonID": "1",
"SalonName": "Affinity",
"SalonEmail": "vay.chaan#th-rce.com",
"SalonPhone": "9999888877",
"SalonMobile": "9999888877",
"SalonAddress": "C-28, Sec-58, India",
"Latitude": "18.5806",
"Longitude": "27.36273",
"Image": null,
"SalonImage": "",
"TimeIntervalminutes": 20,
"AverageRating": 4,
"IsActive": 1
},
{
"SalonID": "3",
"SalonName": "Looks",
"SalonEmail": "rad#th-rce.com",
"SalonPhone": "99998828877",
"SalonMobile": "99998388877",
"SalonAddress": "GP Mall,India",
"Latitude": "",
"Longitude": "",
"Image": null,
"SalonImage": "",
"TimeIntervalminutes": 30,
"AverageRating": 5,
"IsActive": 1
}
]
}

Replace responseJSON with responseString.
You need to convert the string for values. Can you update the string in your question?
You can use this function to convert response string into JSON:
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
String: let str = "{\"name\":\"James\"}"
USAGE: let dict = convertToDictionary(text: str)

Try responseString instead of responseJSON and it will work
Alamofire.request("URL").responseString { response in
print(response)
if let json = response.result.value {
print("JSON: \(json)")
}
}

Change responseJSON to responseString and it will work :)
Alamofire.request("URL").responseString { response in
print(response)
if let json = response.result.value {
print("JSON: \(json)")
}
}

Related

Handle API response without dictionary key parameter SWIFT

I try to decode api response but the values did not have key. How can I decode values to my entity ? I can get values but how can I map values to array of object?
Here is my code:
if let encoded = urlString.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed), let url = URL(string: encoded) {
AF.request(url, method: .get, encoding: JSONEncoding.default).validate().responseData { (response) in
switch response.result {
case .success:
print("Validation Successful)")
if let json = response.data {
do{
let asJSON = try JSONSerialization.jsonObject(with: json, options: []) as? [String: Any]
let dataArray = asJSON?["states"] as? [NSArray]
guard let data = dataArray else { return }
for (i, flight) in data.enumerated() {
for first in flight.enumerated() {
print(first)
}
}
}
catch{
print("JSON Error")
}
}
case .failure(let error):
print(error.errorDescription)
}
}
}
And this is my print
(
4baa88,
"THY3TB ",
Turkey,
1669746477,
1669746477,
"28.782",
"40.9959",
"1127.76",
0,
"118.94",
"301.56",
"-6.5",
"<null>",
"1196.34",
"<null>",
0,
0
)
And this is example of my response
{
"time": 1669744917,
"states": [
[
"4bc855",
"PGT4AE ",
"Turkey",
1669744917,
1669744917,
28.1582,
41.0447,
5791.2,
false,
181.16,
119.99,
-5.85,
null,
5913.12,
"7554",
false,
0
],
[
"4bc846",
"PGT4BC ",
"Turkey",
1669744916,
1669744916,
28.2241,
40.8712,
5608.32,
false,
216.41,
168.34,
-13.33,
null,
5722.62,
"7703",
false,
0
]
]

How can I post request with order of json in swift with alamofire?

I need a payment method for my app and I have to post a request with JSON data for communicate with API. Everything seem correct to me. I can't find any bug in my code but I assume that JSON not post in order. Is this important? Because response said failure but I can't find anything else. If JSON order is important how can I make it? I'm new in swift please help me.
Here my code:
func mainRequestForPayment() {
)
let headers: HTTPHeaders = [
"accept": "application/json",
"content-type": "application/json",
"authorization": "\(self.authValue)",
"x-iyzi-rnd": "\(self.randomString)",
"cache-control": "no-cache"
]
let url = "MY_URL"
let parameters: [String: Any] = [
"locale": "tr",
"conversationId": "123456789",
"price": "1.1",
"paidPrice": "1.1",
"installment": 1,
"paymentChannel": "WEB",
"basketId": "B67832",
"paymentGroup": "PRODUCT",
"paymentCard": [
"cardHolderName": "CARD_HOLDER_NAME",
"cardNumber": "CARD_NUMBER",
"expireYear": "CARD_YEAR",
"expireMonth": "01",
"cvc": "123",
"registerCard": 0
],
"buyer": [
"id": "BY789",
"name": "John",
"surname": "Doe",
"identityNumber": "74300864791",
"email": "email#email.com",
"gsmNumber": "+905350000000",
"registrationAddress": "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1",
"city": "Istanbul",
"country": "Turkey",
"zipCode": "34732",
"ip": "85.34.78.112"
],
"shippingAddress": [
"address": "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1",
"zipCode": "34742",
"contactName": "Jane Doe",
"city": "Istanbul",
"country": "Turkey"
],
"billingAddress": [
"address": "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1",
"zipCode": "34742",
"contactName": "Jane Doe",
"city": "Istanbul",
"country": "Turkey"
],
"basketItems": [
[
"id": "BI101",
"price": "0.3",
"name": "Binocular",
"category1": "Collectibles",
"category2": "Accessories",
"itemType": "PHYSICAL"
],
[
"id": "BI102",
"price": "0.5",
"name": "Game code",
"category1": "Game",
"category2": "Online Game Items",
"itemType": "VIRTUAL"
],
[
"id": "BI103",
"price": "0.2",
"name": "Usb",
"category1": "Electronics",
"category2": "Usb / Cable",
"itemType": "PHYSICAL"
]
],
"currency": "TRY"
]
Alamofire.request(url, method: .post, parameters: parameters , encoding: JSONEncoding.default, headers: headers)
.responseJSON { (response) in
print(parameters)
switch response.result {
case .success(let value):
let swiftyJson = JSON(value)
print ("return as JSON using swiftyJson is: \(swiftyJson)")
case .failure(let error):
print ("error: \(error)")
}
}
}
Where is my fault I can't see? And again is there any way to make order in post request? Thanks all.
I get that response:
return as JSON using swiftyJson is: {
"conversationId" : "123456789",
"locale" : "tr",
"errorCode" : "1000",
"status" : "failure",
"systemTime" : 1579858355103,
"errorMessage" : "Invalid signature"
}
JSON order isn't typically important, as the JSON spec doesn't define it as a requirement for JSON objects, but some poorly engineered backends do require it. You really need to check the requirements of the backend you're communicating with.
Additionally, Swift's Dictionary type is arbitrarily ordered, and that order may change between runs of your app as well as between versions of Swift used to compile your code.
Finally, Swift's JSONEncoder, and Apple's JSONSerialization type both offer no way to require strict ordering. At most, JSONSerialization offers the .sortedKeys option, which will give you a guaranteed (alphabetical) order, but it may not be the order you declared your parameters in. Using an alternate Encoder, if you have Codable types (which I recommend instead of SwiftyJSON), may give you a better guarantee of order, but you should only really care if it's a requirement of your backend.
As an aside, I suggest you use the static HTTPHeader properties for your HTTPHeaders value, instead of using raw strings, it's much more convenient. For example:
let headers: HTTPHeaders = [.accept("application/json"),
.contentType("application/json")]
Use this class
//////////////////////////////////////////////
import Foundation
import UIKit
import Alamofire
class ServicesClass_New : NSObject
{
var delegate : ServicesClassDelegate!
typealias CompletionBlock = (_ result : Dictionary<String, Any>?, _ error : Error?) -> Void
typealias CompletionDataBlock = (_ result : Data?) -> Void
typealias ProgressBlock = (_ progressData : Progress) -> Void
//MARK: Shared Instance
static let sharedInstance : ServicesClass = {
let instance = ServicesClass()
return instance
}()
static func getDataFromURlWith(url:String,parameters:Dictionary<String, Any>?, requestName:String,completionBlock : #escaping CompletionBlock)
{
print("net available")
Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
switch(response.result) {
case .success(_):
if let data = response.result.value
{
//print(response.result.value!)
//print(data)
var dic : Dictionary<String,Any> = Dictionary()
if data as? Array<Dictionary<String,Any>> != nil
{
dic["data"] = data as? Array<Dictionary<String,Any>>
completionBlock(dic,nil)
}
else
{
completionBlock(data as? Dictionary<String,Any>,nil)
}
}
break
case .failure(_):
print(response.result.error!)
completionBlock(nil ,response.result.error!)
break
}
}
}
static func postDataFromURL(url:String,parameters:Dictionary<String, Any>?, requestName:String,completionBlock : #escaping CompletionBlock)
{
print("net available")
//application/json
//multipart/form-data
let hders : HTTPHeaders = [ "Content-Type" : "application/json"] as [String : String]
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: hders).responseJSON { response in
switch(response.result) {
case .success(_):
if let dict = response.result.value
{
let data = dict as! Dictionary<String,Any>
// print(response.result.value!)
// print(data)
completionBlock(data as Dictionary,nil)
}
break
case .failure(let error):
print((error as NSError).localizedDescription)
completionBlock(nil ,response.result.error!)
print("\(error.localizedDescription)")
break
}
}
}
static func downloadFile(strUrl : String, progressBlock : #escaping ProgressBlock, completionBlock : #escaping CompletionDataBlock)
{
let utilityQueue = DispatchQueue.global(qos: .utility)
Alamofire.request(URL.init(string: strUrl)!).downloadProgress(queue: utilityQueue, closure: { (progress) in
progressBlock(progress)
})
.responseData { (response) in
if let data = response.result.value
{
completionBlock(data)
}
else
{
completionBlock(nil)
}
}
}
static func uploadData(url:String,parameters:Dictionary<String, Any>,requestName:String,arrImg:[UIImage],arrVideos:[URL],completionBlock : #escaping CompletionBlock)
{
print("net available")
let hders = [
"Content-Type": "application/json"
]
Alamofire.upload(multipartFormData:
{
MultipartFormData in
for img in arrImg
{
let imageData = UIImageJPEGRepresentation(img , 0.8)!
MultipartFormData.append(imageData, withName: "image" , fileName:"file\(index).jpg", mimeType:"image/jpeg")
}
index = 0
for video in arrVideos
{
index = index + 1
var videoData : Data = Data()
do
{
videoData = try Data.init(contentsOf: URL.init(fileURLWithPath: video.path))
MultipartFormData.append(videoData, withName: "video", fileName:"file\(index).mp4",mimeType: "video/mp4")
}
catch
{
}
}
for (key, value) in parameters
{
MultipartFormData.append((value as! String).data(using: String.Encoding.utf8)!, withName: key)
}
}, to:url,method:.post,headers:hders, encodingCompletion: {
encodingResult in
//["content-type" : "application/json"]
switch encodingResult
{
case .success(let upload, _, _):
print("image uploaded")
upload.responseJSON { response in
if let JSON = response.result.value
{
print("JSON: \(JSON)")
}
if let dict = response.result.value
{
let data = dict as! Dictionary<String,Any>
print(response.result.value!)
print(data)
completionBlock(data as Dictionary,nil)
}
}
break
case .failure(let encodingError):
completionBlock(nil ,encodingError)
break
}
} )
}
}
/// call protocals where you want to call API.
//There is multiple Methods like : GET, POST
....

Send JSON with array of objects as parameter in Alamofire with swift

I am very new with Swift and Alamofire, what I want to accomplish is to send a data structure, like this:
{
"name" : "Test name",
"intention" : "Purpose of practice test",
"id_frequency" : "1",
"member": [
{
"id_member" : "1",
"email" : "member1#gmail.com",
"id_member_type" : 1
},
{
"id_member" : "4",
"email" : "member2#gmail.com",
"id_member_type" : 3
},
{
"id_member" : "7",
"email" : "member3#gmail.com",
"id_member_type" : 3
},
{
"id_member" : "5",
"email" : "member4#gmail.com",
"id_member_type" : 3
},
{
"id_member" : "6",
"email" : "member5#gmail.com",
"id_member_type" : 3
}
]
}
The way I am proceeding to structure the desired json, is as follows:
var membersArray = [AnyObject]()
for i in 0..<members.count {
let json: [String: Any] = [
"id_member": members[i].idMember!,
"email": members[i].email!,
"id_member_type": "\(Int(members[i].idMemberType)!)",
]
membersArray.append(json as AnyObject)
}
let jsonMembers = JSON(membersArray)
let jsonObject: [String: Any] = [
"member" : jsonMembers,
"name": name!,
"intention": intention!,
"id_frequency": frequency!
]
let jsonUpdate = JSON(jsonObject)
With this structured json, lines above (jsonUpdate). I proceed to execute the webService.
WevServices.createRequest(requestInfo: jsonUpdate) { (result) in
print(result)
}
My webservice method, looks like this:
static func createRequest(requestInfo: JSON, completion: #escaping (_ result: String) -> Void){
let url = URL(string: "http://ws.someURL.com/CreateRequest")
let parameters: [String : Any] = ["name" : "\(requestInfo["name"])", "intention" : "\(requestInfo["intention"])", "id_frequency" : "\(requestInfo["id_frequency"])", "member": requestInfo["member"]]
Alamofire.request(url!, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).responseString { response in
print(response)
}
}
I'm get an error from the server that the send data would not be correct.
Note: My application use Lumen as backend.
The best way for doing what you need is :
func JSONToString(json: [String : String]) -> String?{
do {
let mdata = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) // json to the data
let convertedString = String(data: mdata, encoding: String.Encoding.utf8) // the data will be converted to the string
print("the converted json to string is : \(convertedString!)") // <-- here is ur string
return convertedString!
} catch let myJSONError {
print(myJSONError)
}
return ""
}
and for alamofire request do this :
static func createRequest(requestInfo: [String :String], completion: #escaping (_ result: String) -> Void){
let url = URL(string: "http://ws.someURL.com/CreateRequest")
let parameters: [String : Any] = ["request" : JSONToString(json : requestInfo)!]
Alamofire.request(url!, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).responseString { response in
print(response)
}

Cannot update data in API using .PUT request in Alamofire

I am creating an Event app where in the user should tap Check In Button to register for the event. registered_flag : false will be true and registered_type: 0 will be 1 once the user tapped the button. But as I build and run the app, error appeared that says
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
0." UserInfo={NSDebugDescription=Invalid value around character 0.})).
I am not really confident regarding the content of my codes in my APIService. Hope someone will help me to correct my codes so I could build and run my app successfully. Thank you so much.
application/json that needs to be updated which inside event_participant
{
"registered_flag": false,
"registration_type": 0
}
event_participant
"event_participants": [
{
"participant_id": "70984656-92bc-4c36-9314-2c741f068523",
"employee_number": null,
"last_name": "Surname",
"first_name": "FirstName",
"middle_name": null,
"display_name": "Surname, FirstName ",
"department_name": "Department",
"position_name": "Developer",
"registered_flag": false,
"registered_datetime": "2018-09-13T08:54:40.150",
"registration_type": 0,
"delete_flag": false,
"manual_reg_flag": false,
"out_flag": false,
"out_datetime": null,
"classification": 6,
"others": "Guest"
}
}
API Service using PUT request in Alamofire
func updateParticipant(updateType: UpdateParticipantType,
participantID: String,
completionHandler: #escaping(([Attendee]?, Error?) -> Void)) {
let updateParticipantURL = URL(string: "\(REGISTER_PARTICIPANT_URL)/\(updateType)/\(participantID)")
let headers: HTTPHeaders = [
"Content-Type": "application/json"
]
let parameters: Parameters = [
"registered_flag": false,
"registration_type": 0
]
Alamofire.request(updateParticipantURL!, method: .put, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
switch response.result {
case .success:
print("Done")
if let jsonArray = response.result.value as? [[String : Any]] {
for anItem in jsonArray {
if let eventparticipant = anItem["event_participants"] as? [[String : Any]] {
var extractedAttendee = [Attendee]()
for participant in eventparticipant{
print(participant)
let success = Attendee.init(JSON: participant)
extractedAttendee.append(success!)
}
completionHandler(extractedAttendee, nil)
}
}
}
case .failure(let error):
completionHandler(nil, error)
}
}
}
Struct for Attendee
struct Attendee: Decodable {
let id: String
let employeeNumber: String?
let lastName: String
let firstName: String
let middleName: String
let displayName: String
let department: String
let position: String
let registeredFlag: Bool
let registeredDateTime: Date?
let registrationType: Int
let deleteFlag: Bool
let manualFlag: Bool
let outFlag: Bool
let outDateTime: Date?
let classification: Int?
let others: String?
postman response

Swift Alamofire Request Error - Extra Argument in call

I am getting an error when I am trying to request using Alamofire. The error says that there is an 'extra argument in call'.
class SwiftStockKit {
class func fetchStocksFromSearchTerm(term: String, completion:#escaping (_ stockInfoArray: [StockSearchResult]) -> ()) {
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async {
let searchURL = "http://autoc.finance.yahoo.com/autoc"
Alamofire.request(.GET, searchURL, parameters: ["query": term, "region": 2, "lang": "en"]).responseJSON { response in
if let resultJSON = response.result.value as? [String : AnyObject] {
if let jsonArray = (resultJSON["ResultSet"] as! [String : AnyObject])["Result"] as? [[String : String]] {
var stockInfoArray = [StockSearchResult]()
for dictionary in jsonArray {
stockInfoArray.append(StockSearchResult(symbol: dictionary["symbol"], name: dictionary["name"], exchange: dictionary["exchDisp"], assetType: dictionary["typeDisp"]))
}
dispatch_async(dispatch_get_main_queue()) {
completion(stockInfoArray: stockInfoArray)
}
}
}
}
}
}
The line that is giving me an error is:
Alamofire.request(.GET, searchURL, parameters: ["query": term, "region": 2, "lang": "en"]).responseJSON { response in
if anyone could fix this I would be really grateful, thanks
Try change your request to something like this:
Alamofire.request(searchURL, method: .get, parameters: ["query": term, "region": 2, "lang": "en"], encoding: JSONEncoding.default, headers: nil)

Resources