my error is
unsuccessfullresponseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}))
here my webservice by alamofire
IBAction func loginbtn(_ sender: Any) {
runPutRequest()
}
func runPutRequest() {
let parameters: Parameters = [
"UserName" : "ABC",
"Password" : "pass"
]
func runPutRequest() {
let par: Parameters = [
"UserName" : "dominic.koh#circle8.asia",
"Password" : "password2"
]
let header: HTTPHeaders = [ "Accept": "application/json" ]
Alamofire.request("http://circle8.asia:8081/Onet.svc/UserLogin",method:.post, parameters: par , encoding: URLEncoding.queryString,headers:header).responseJSON { (resDataLogin) -> Void in
// print(resDataLogin)
switch resDataLogin.result
{
case.success(let data) :
print("YOUR Details>> ",data)
break
case.failure(let error) :
print("unsuccessfull\(error)");
break
}
}
}
Related
Guys I need to send parameters described in the image value where content type is multipart/form-data. Im having difficulty in sending only package_json parameter.
The problem is I don't know how do I send multiple package_json values as parameter? I can send one value like this:
let param = [
"outletId : "1",
"vehicleId" : "1",
"instructions" : tvInstructions.text,
"package_json" : "[{\"packageId\":\"1\"}]",
"addressId" : "1"
]
Above i'm able to send package_json = [{"packageId": 1}] as String as my function below sends parameters as [String : String] and images of Data type as [String : Any]. Im having problem sending multiple values in package_json. For eg. something like this: [{"packageId": 1}, {"packageId": 2}, {"packageId": 3}] and so on. Here's the function that i'm using to send parameters:
func postrequest(_ request: String, onPath imagesData:[Data]?,_ imageName : String, andParameter parameters: [String:String]?, withCompletion response: #escaping serviceCompletion) {
let headers: HTTPHeaders
headers = ["Content-type": "multipart/form-data"]
AF.upload(multipartFormData: { multiPart in
if let allParams = parameters {
for (key, value) in allParams {
multiPart.append(value.data(using: .utf8)!, withName: key)
}
}
for imageData in imagesData ?? [] {
multiPart.append(imageData, withName: "\(imageName)", fileName: "file.jpg", mimeType: "image/jpg")
}
}, to: request, usingThreshold: UInt64.init(),
method: .post,
headers: headers).response { (res) in
if((res.error == nil)){
do {
response(res.data,res.error)
}
}
else{
// hideHud()
response(res.data,res.error)
}
}
}
I tried to convert function to send [String: Any] data but found out we can only send as [String : String] along with images as [String : Any].
I just want to know if there is any way to modify "package_json" : "[{\"packageId\":\"1\"}]" so I can send [{"packageId": 1}, {"packageId": 2}, {"packageId": 3}]?
Just in case, this is how im calling above function and sending parameters:
func sendData() {
let param = [
"outletId" : "1",
"vehicleId" : "1",
"instructions" : tvInstructions.text,
"package_json" : "[{\"packageId\":\"1\"}]",
"addressId" : "1"
]
ApiNetworkManager.shared.postrequest(Api.completeUrl, onPath: [], "", andParameter: param) { (response, err) in
ApiNetworkManager.shared.hideHud()
debugPrint(param)
let json = JSON.init(response!)
debugPrint(json)
if err == nil {
if err == nil && response != nil {
if json.dictionaryValue["success"]?.stringValue == "1" {
//Add your code here
}
else{
let message = json.dictionaryValue["message"]?.stringValue
self.showAlert(Message: message ?? "Error")
}
} else {
// hideHud()
print(err?.localizedDescription as Any)
let message = json.dictionaryValue["message"]?.stringValue
self.showAlert(Message: message ?? "Error")
}
}
else{
ApiNetworkManager.shared.hideHud()
let message = err?.localizedDescription
self.showAlert(Message: message ?? "Error")
}
}
}
I have checkboxes required for product return on a page with more than one product, and when I press a checkbox, I want to store the id and quantity of the selected product in the items in the post parameter that I want to send.But, I cannot send the correct data. How can I send correct data?
{
"reasonId" : "001",
"cancel" : "true",
"description": "" ,
"items": [
{
"id": "874a8064-bebf-41c3-98a8-6ac39a54156a",
"quantity" : 480
},
{
"id": "d7af8722-58cb-4bd0-9927-47de44ba2e0b",
"quantity" : 2
},
{
"id": "f799d66e-cfcd-4f2b-9603-1facf2fedbea",
"quantity" : 1
},
{
"id": "5ea0c31f-952a-4fbc-b623-9086030193ad",
"quantity" : 17
}
]
}
I can print the id and quantity of the selected product.
private func createCheckBox(_ model : OrderDetailItems, tag: Int) -> UIView {
let rootView = UIView()
returnItemCount = model.definition?.count
var checkBox: ViewCheckLabel!
checkBox = ViewCheckLabel(text: "",
range: "",
action: {
// CHECKK SELECT OR NOT SELECT
checkBox.buttonCheck.checkboxAnimation {
if checkBox.buttonCheck.isSelected {
print(model.quantity)
print(model.id)
} else {
}
}
})
This is my post request
func cancelOrderApi() {
if let parentVC = parentViewController as? MyProfileViewController {
parentVC.startActivityIndicator(mainView: parentVC.view)
let parameters : Parameters = [
"reasonId" : reasonId,
"cancel" : isOrdrReturnable,
"description": "",
"items" : ""
]
NetworkLayer.request(Router.returnOrder(parameters, orderReturnId ?? "")).responseDecodable(of: OrderCancel.self) { (response) in
switch response.result {
case .failure(let error):
Logger.shared.debugPrint("Error while fetching tags: \(String(describing: error))")
return
case .success(let response):
if response.code == 200 {
parentVC.showAlert(mesg: response.message ?? "Siparişiniz İade edilmiştir", title: "Başarılı")
} else {
parentVC.showAlert(mesg: response.message ?? "", title: "Hata")
Logger.shared.debugPrint(response.message ?? "")
}
Logger.shared.debugPrint(response)
}
DispatchQueue.main.async {
parentVC.stopActivityIndicator()
parentVC.profileTableView.reloadData()
}
}
}
}
I am not entirely sure what you want to achieve, since the question is unclear, however here is a tip how to create Data object (can be later inserted into Url request) from your JSON file. Firstly manually copy your JSON file somewhere to your project and give it name yourJSONFile , then you can create Data object with create createDataFromJson() function.
func createDataFromJson() -> Data? {
if let path = Bundle.main.path(forResource: "yourJSONFile", ofType: "json") {
do{
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
return data
} catch {
print("catched : \(error.localizedDescription) ❌")
return nil
}
} else {
return nil
}
}
I have a JSON file with this struct:
{
"example": {
"projects": [
{ "projectname" : "abc",
"date" : "20200930",}
{ "projectname" : "bac",
"date" : "20200803",}
]
}
}
I want to update first projectname, but not the date connected to it. But the AF.request method give me back error 400 (Invalid JSON body passed.)
let user = "username"
let password = "password"
let params = ["example":
["projects":
["projectname": "New Name"]
]
]
let credentialData = "\(user):\(password)".data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let base64Credentials = credentialData.base64EncodedString()
let headers : HTTPHeaders = [
"Authorization": "Basic \(base64Credentials)",
"Accept": "application/json",
"Content-Type": "application/json" ]
AF.request("https://example.com/api", method: .put, parameters: params, headers: headers).responseJSON { AFdata in
do {
guard let jsonObject = try JSONSerialization.jsonObject(with: AFdata.data!) as? [String: Any] else {
print("Error: Cannot convert data to JSON object")
return
}
guard let prettyJsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) else {
print("Error: Cannot convert JSON object to Pretty JSON data")
return
}
guard let prettyPrintedJson = String(data: prettyJsonData, encoding: .utf8) else {
print("Error: Could print JSON in String")
return
}
print(prettyPrintedJson)
} catch {
print("Error: Trying to convert JSON data to string")
return
}
}
Thanks for your help!
I believe you are missing the encoder parameter in you request:
AF.request("https://example.com/api", method: .put, parameters: params, headers: headers, encoder: JSONParameterEncoder.default).responseJSON { AFdata in
Without it Alamofire cannot know that your parameters should be encoded as JSON.
I'm having difficulty with a parameter which contains a Json array using Alamofire
Here is a string of my Json:
"[{\"id\":546836102,\"count\":1},{\"id\":216479424,\"count\":1}]"
Here is my code where I make the request:
let data = (params["cart"] as! String).data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .fragmentsAllowed) as? [Dictionary<String, Int>] {
let parameters: Parameters = [
"address_id": params["address_id"] as! Int,
"delivery_day": params["delivery_day"] as! String,
"delivery_hour": params["delivery_hour"] as! Int,
"cart": jsonArray,
"via": params["via"] as! String
]
Alamofire.request(Global.baseURL + "orders/finish", method: .post, parameters: parameters, encoding: URLEncoding.default, headers: header)
.responseSwiftyJSON {
Printing out my parameters
["cart": [["id": 546836102, "count": 1], ["count": 1, "id": 216479424]], "address_id": 641589205, "delivery_day": "1399-01-20", "delivery_hour": 21, "via": "ios"]
Backend must receive the cart as below:
[
{
"id": 123456,
"count": 2
},
{
"id": 654321,
"count": 3
}
]
But instead it gets the data like this:
{
"delivery_hour" : "21",
"delivery_day" : "1399-01-20",
"cart" : [
{
"count" : "1"
},
{
"id" : "546836102"
},
{
"count" : "1"
},
{
"id" : "216479424"
}
],
"via" : "ios",
"address_id" : "641589205"
}
I have tried JSONEncoding and URLEncoding options by Alamofire but nothing seems to work and this is the closest I've gotten to the API template so far.
What am I doing so wrong here?
// MARK: - Update
So I updated to the latest version of Alamofire and still no good results :(
Here is the code:
let payload = MyParameters(address_id: 641589205, delivery_day: "1399-01-21", delivery_hour: 21, cart: items, via: "ios")
AF.request(url, method: .post, parameters: payload, encoder: JSONParameterEncoder.default, headers: .init(header), interceptor: nil).response { dataResponse in
switch dataResponse.result {
case .success(let value):
if dataResponse.response?.statusCode == 200 {
let json = JSON(value!)
completionHandler(json, nil)
} else {
print(dataResponse.response?.statusCode ?? -1)
}
case .failure(let error):
print(error)
completionHandler(nil, error.localizedDescription)
}
}
My payload looks exactly what I want it to be
{
"cart" : [
{
"count" : 1,
"id" : 546836102
},
{
"count" : 1,
"id" : 216479424
}
],
"via" : "ios",
"address_id" : 641589205,
"delivery_day" : "1399-01-21",
"delivery_hour" : 21
}
But then again the endpoint receives this:
{
"{\"delivery_day\":\"1399-01-21\",\"address_id\":641589205,\"delivery_hour\":21,\"cart\":" : {
"{\"id\":546836102,\"count\":1},{\"id\":216479424,\"count\":1}" : null
}
}
Using Alamofire 4, you can't send arrays using the method you've shown, as the Parameters type is [String: Any]. You're also not using the correct ParameterEncoding. If you want to send a JSON body, you need to use the JSONEncoding. What you can do is manually serialize the array into a URLRequest and make that request using Alamofire.
Additionally, if you update to Alamofire 5, Encodable parameters are now supported, so you if you can define your parameters as an Encodable type, sending them would be as easy as passing an array.
AF.request(..., parameters: [some, encodable, values], encoder: JSONEncoder.default)...
i want to post array of dictionaries in alamofire, but some how it is not posting.i can use many ways but still not find the proper answer on it. Showing error "Extra argument 'method' in call" . Here is my code.
let userToken: HTTPHeaders = [
"Content-Type": "application/json"
]
let parm = [
[
"EmployeeID": id,
"Longitude": longitude,
"Latitude": latitude,
"GeoTime": dateString,
"UserToken": "g98XQdy8B}rQ7?Q"
]
]
postAttandance(apiUrl: postAttandanceURL, parameter: parm , tiket: userToken){
(done) -> Void in
if done{
}
}
func postAttandance(apiUrl : String , parameter : [[String : Any]] , tiket : HTTPHeaders , completion : #escaping (_ done : Bool) -> Void ){
Alamofire.request(apiUrl, method : .post , parameters : parameter ,encoding : JSONEncoding.default, headers : tiket).responseJSON { (response) in
if response.result.isSuccess{
let responsejson : JSON = JSON(response.result.value!)
completion(true)
}
}
}