post array of json with alamofire swift - ios

How can i post array of json objects with alamofire in swift?
my final data (which i want to post) looks like:
temp = [{
"time": 1,
"score": 20,
"status": true,
"answer": 456
},
{
"time": 0,
"score": 0,
"status": false,
"answer": 234
},
{
"time": 0,
"score": 20,
"status": true,
"answer": 123
}
]
i got hint that i have to create custom parameter encoding but i am confused how can i do that. Someone please help me.
my current code looks like
let parameters: Parameters = [
"answers": temp,
"challenge_date": "2019-03-01"
]
Alamofire.request("...url", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.responseJSON {
response in
if
let status = response.response ? .statusCode {
let classFinal: JSON = JSON(response.result.value!)
if (status > 199 && status < 300) {
self.dismiss(animated: true)
} else {
}
}
}

In your code change method .put to .post, and not required to SVProgressHUD.dismiss() in else, because you already dismiss before if else part
Also, you need to convert your JSON string(temp variable) to array and then pass with the parameter.
let parameters: Parameters = [
"answers": temp,
"challenge_date": "2019-03-01"
]
Alamofire.request("...url", method: .post, parameters: parameters, encoding: JSONEncoding.default , headers: headers)
.responseJSON { response in
if let status = response.response?.statusCode {
let classFinal : JSON = JSON(response.result.value!)
SVProgressHUD.dismiss()
if status > 199 && status < 300 {
self.dismiss(animated: true)
}
}
}

I hope your Parameters class follows Codable protocol.
As far as I see, you are getting an error parsing that object to JSON. Hence that is the source of your error.
Could you also add code for your Parameters class / struct

First, convert your Temp
Array into String
than pass in that in parameters of Alamofire.
extension NSArray {
func toJSonString(data : NSArray) -> String {
var jsonString = "";
do {
let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
} catch {
print(error.localizedDescription)
}
return jsonString;
}
}

Related

How to Arrangement array before send request to alamofire in swift

let request = NSMutableDictionary()
request.setDictionary([ "merchant_reference":getRandomMerchant, "merchant_identifier":"e54638eb", "access_code":"hRRVGXrIpHSYoH19Ebwt", "signature": base64Str, "service_command":"OTP_GENERATE", "language":"en", "payment_option":"VALU", "phone_number":"01008606003", "merchant_order_id":getRandomMerchant, "amount":getTotal, "currency":"EGP", "products":[ [ "product_name": getName, "product_price": getTotal, "product_category":getProductType ] ] ])
Alamofire.request(URLAPi.URL_Payment_Api ,
method : .post ,
parameters : (request as! Parameters) ,
encoding: JSONEncoding.default
).responseJSON { (response) in
debugPrint(response)
if response.result.isSuccess {
let jsonpayfortrequest : JSON = JSON(response.result.value!)
var resultsArray = jsonpayfortrequest.arrayValue
var sortedResults = resultsArray.sorted { $0.stringValue > $1.stringValue }
print(jsonpayfortrequest)
print(resultsArray)
print(sortedResults)
print(jsonpayfortrequest.sorted(by: {$0 > $1}))
let passobjectforrootclasspayfort = OTPGenrateModel(fromJson: jsonpayfortrequest)
print(passobjectforrootclasspayfort.transaction_id!)
SVProgressHUD.dismiss()
} else {
print("error connection") SVProgressHUD.dismiss()
}
}
Try this way, Hope, that will fixe your issue. If it doesn't, please reply
let parameters: [String: Any] = [
"merchant_reference":getRandomMerchant,
"merchant_identifier":"e54638eb",
"access_code":"hRRVGXrIpHSYoH19Ebwt",
"signature": base64Str,
"service_command":"OTP_GENERATE",
"language":"en",
"payment_option":"VALU",
"phone_number":"01008606003",
"merchant_order_id":getRandomMerchant,
"amount":getTotal,
"currency":"EGP",
"products": [
[
"product_name": getName,
"product_price": getTotal,
"product_category":getProductType
]
]
]
Alamofire.request(URLAPi.URL_Payment_Api , method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
// Insert your code here
}

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
....

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)

swiftyjson getting string from json array

I am using alamofire and swiftyjson to get it. I need to get string "ubus_rpc_session", I tryed this way, but I get an array, I need to get string. Could you help me?
Alamofire.request(URL, method: .post, parameters: param, encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
let token = json["result"].arrayValue.map({$0["ubus_rpc_session"].stringValue})
print(token)
{ "jsonrpc":"2.0",
"id":1,
"result":[
0,
{
"ubus_rpc_session":"07e111d317f7c701dc4dfde1b0d4862d",
"timeout":300,
"expires":300,
"acls":{
"access-group":{
"superuser":[
"read",
"write"
],
"unauthenticated":[
"read"
]
},
"ubus":{
"*":[
"*"
],
"session":[
"access",
"login"
]
},
"uci":{
"*":[
"read",
"write"
]
}
},
"data":{
"username":"root"
}
}
]
}
Try this
//Getting an array of string from a JSON Array(In their documents)
let arrayNames = json["users"].arrayValue.map({$0["name"].stringValue})
if let tempArray = json["result"].arrayValue {
for item in tempArray {
print(item)
if let title = item["ubus_rpc_session"].string {
println(title)
}
}
}
Or check this
let value = tempArray[1].dictionaryObject!
print(value["ubus_rpc_session"]!)

SwiftyJson get value of json from complicated structure of JSON

This my json.file:
[
{
"date_range": "2016-11-01-2016-12-31",
"order_status_id": 3,
"jobs": [
{
"date": "2016-11-14",
"job": [
{
"id": 143608,
"pickup_worker_id": null,
"drop_off_worker_id": 57
}
]
}
]
}
{
"date_range": "2016-11-01-2016-12-31",
"order_status_id": 2,
"jobs": [
{
"date": "2016-11-16",
"job": [
{
"id": 143238,
"pickup_worker_id": null,
"drop_off_worker_id": 12
},
{
"id": 13218,
"pickup_worker_id": null,
"drop_off_worker_id": 42
}
]
},
{
"date": "2016-11-19",
"job": [
{
"id": 141238,
"pickup_worker_id": null,
"drop_off_worker_id": 12
}
]
}
]
}
]
This my code for swiftyjson:
Alamofire.request(Constants.web_api+api_get_orders, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: Constants.headers ).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
print("All Data JSON \(swiftyJsonVar)")
print("date range1\(swiftyJsonVar["date_range"])")
print("date range2\(swiftyJsonVar["date_range"].stringValue)")
print("jobs1 \(swiftyJsonVar["jobs"].arrayObject)")
print("jobs2 \(swiftyJsonVar["jobs"].array)")
print("jobs3 \(swiftyJsonVar["jobs"])")
print("jobs date \(swiftyJsonVar["jobs"]["date"].stringValue)")
print("jobs date \(swiftyJsonVar["jobs"]["job"]["drop_off_worker_id"].stringValue)")
}
The output , all is null or nil except All Data JSON (swiftyJsonVar). How can I get value of date_range, drop_off_worker_id ? I really hope someone can help me. I spend a lot of time for solve it but still can't solve it.
Your JSON response is Array not Dictionary, so you need to access its first object to get the detail you want.
if let dateRange = swiftyJsonVar[0]["date_range"].string {
print(dateRange)
}
if let worker_id = swiftyJsonVar[0]["jobs"][0]["job"][0]["drop_off_worker_id"].int {
print(worker_id)
}
Edit: If you have multiple object in your root than get all the dateRange and worker_id in for loop.
for subJson in swiftyJsonVar.array {
if let dateRange = subJson["date_range"].string {
print(dateRange)
}
for jobsJson in subJson["jobs"].array {
for jobJson in jobsJson["job"].array {
if let worker_id = jobJson["drop_off_worker_id"].int {
print(worker_id)
}
}
}
}
Please try, by referring the index of the element in the array.
Alamofire.request(Constants.web_api+api_get_orders, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: Constants.headers)
.responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
print("All Data JSON \(swiftyJsonVar)")
print("date range1\(swiftyJsonVar[0]["date_range"])")
print("date range2\(swiftyJsonVar[0]["date_range"].stringValue)")
print("jobs1 \(swiftyJsonVar[0]["jobs"].arrayObject)")
print("jobs2 \(swiftyJsonVar[0]["jobs"].array)")
print("jobs3 \(swiftyJsonVar[0]["jobs"])")
print("jobs date \(swiftyJsonVar[0]["jobs"]["date"].stringValue)")
print("jobs date \(swiftyJsonVar[0]["jobs"]["job"]["drop_off_worker_id"].stringValue)")
}

Resources