How to Arrangement array before send request to alamofire in swift - ios

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
}

Related

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

post array of json with alamofire swift

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;
}
}

Request to Alamofire

I need to send a request to the server like this
[{
"Case":"add",
"Table":"user",
"Field":["Email","Password"],
"Value":["a","a"],
"Duplicate":["Email"],
"SecureEncrpt":"Password",
"SecureDecrpt":"Password"
}]
and I'm using alamofire for the network process, and im using request structure like this
let loginparas = [
"Case": "add",
"Table":"user",
"Field":["Email","Password"],
"Value":[details,pass],
"Duplicate":["Email"],
"SecureEncrpt":"",
"SecureDecrpt":""
] as AnyObject
let parameters = loginparas as! Parameters
How can I get exactly like that format?
let loginparas = [
"Case": "add",
"Table":"user",
"Field":["Email","Password"],
"Value":[details,pass],
"Duplicate":["Email"],
"SecureEncrpt":"",
"SecureDecrpt":""
] as [String:Any]
Alamofire.request( url , method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers ).responseJSON { response in
if response.result.isSuccess {
guard let json = response.result.value as? NSArray else { return }
for j in json {
let jsonValur = j as? [String:Any]
let case = jsonValue["Case"] as? String
...
...
...
}
}
}

Alamofire: send parameter

I want to post data as parameter like this:
{
"data":
[
{
"nik" : "lalaal"
}
]
}
How do I write to these parameters in Swift 3 using Alamofire?
i tried :
let parameter: Parameters = [
"data":[[
"nik" : self.nik,
"check_type" : "IN",
"tanggal" : "01-08-2017 18:22:00",
"long" : String(locationList[projectChoosen].long!),
"lat" : String(locationList[projectChoosen].lat!),
"id_loc" : locationList[projectChoosen].id_project,
"id_project" : nil,
"nama_project" : locationList[projectChoosen].nama_project,
"barcode" : "",
"foto": "",
"mime_type" : "image/jpeg"
]]
]
You can use below code.
let dicRequest: NSDictionary = ["userid" : "test", "password" : "test123"]
let postParams:NSDictionary = [
"data": dicRequest
]
let requestURL: String = String(format: "%#/Login", serverURL)
Alamofire.request(requestURL, method: .post, parameters: postParams as? [String : AnyObject], encoding: JSONEncoding.default, headers: [:])
.responseJSON { response in switch response.result {
case .success(let JSON):
print("response :-----> ",response)
case .failure(let error):
print("Request failed with error: \(error)")
}
}
You can create a Dictionary object first in this formate
{
"data":
[
{
"nik" : "lalaal"
}
]
}
After that you can convert this using NSJSONSerlisation to json string
And than post using Almofire.
let array: [[String: String]] = [["nik": "lalaal"]]
let data = try JSONSerialization.data(withJSONObject: array, options: JSONSerialization.WritingOptions.prettyPrinted)
let string = String(data: data, encoding: String.Encoding.utf8)
let postParam: [String: String] = ["data": string]
let _ = Alamofire.request(apiType.url!, method: apiType.type!,parameters: postParam, encoding: JSONEncoding.prettyPrinted, headers: nil).validate(statusCode: 200..<500).responseJSON { (response) in
}
Here is a sample request using Alamofire and posting a dictionary as parameters:
let dataArray: [[String: String]] = [["nik": "lalaal"]]
let param: [String: [Any]] = ["data": dataArray]
Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: nil).responseJSON { response in }
I use :
let dataIn: [String: String] = ["param1": "value1"]
let paramGo: [String: [String: String]] = ["data_title": dataIn]
Alamofire.request(url, method: .post, parameters: paramGo, encoding: JSONEncoding.default, headers: nil).responseJSON { response in }

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"]!)

Resources