I'm currently working on an iOS app, and recently I faced an obstacle, basically the API endpoint I'm trying to consume requires a JSON object as a POST parameter in this format.
{
json: {
product_report: [
{
"id_assigned_pos": someid,
"id_user": someid,
"number": somenumber,
},
{
"id_assigned_pos": someid,
"id_user": someid,
"number": somenumber,
},{
"id_assigned_pos": someid,
"id_user": someid,
"number": somenumber,
}
]
}
}
I'm having a hard time figuring out how to achieve this using Alamofire and swift 4.
I'd appreciate someone's help.
Thanks!
let parameters = [
"json": [
"product_report": [
[
"id_assigned_pos": 1,
"id_user": 1,
"number": 1
],
[
"id_assigned_pos": 1,
"id_user": 1,
"number": 1
],
[
"id_assigned_pos": 1,
"id_user": 1,
"number": 1
],
]
]
]
Alamofire.request(url, method:.post, parameters:parameters, headers:headers).responseJSON { response in
// Here is the response
} `
You can try this one:
var dict : [String: Any] = [:]
dict["type"] = "Step"
dict["data"] = ["2015-08-02": 8574];
let params: [String: Any] = ["r_id": "someName",
"data": String.jsonString(data: dataDict)];
Here jsonString is an extension of String
static func jsonString(data : Any) -> 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
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
....
Hi have an application which collects data from an api and I use Alamofire and swiftyJSON. the current challenge I am facing now is that I have different dictionaries in one array and I want to be able to retun back specific items in the dictionary. this is the array I am working with
Json
[
{
"images": [
{
"id": 8,
"original": "http://127.0.0.1:8000/media/images/products/2018/05/f3.jpg",
"caption": "",
"display_order": 0,
"date_created": "2018-05-26T17:24:34.762848Z",
"product": 13
},
{
"id": 9,
"original": "http://127.0.0.1:8000/media/images/products/2018/05/f5.jpg",
"caption": "",
"display_order": 1,
"date_created": "2018-05-26T17:24:34.815214Z",
"product": 13
},
{
"id": 10,
"original": "http://127.0.0.1:8000/media/images/products/2018/05/f2.jpg",
"caption": "",
"display_order": 2,
"date_created": "2018-05-26T17:25:19.117271Z",
"product": 13
},
{
"id": 11,
"original": "http://127.0.0.1:8000/media/images/products/2018/05/f4.jpg",
"caption": "",
"display_order": 3,
"date_created": "2018-05-26T17:25:19.155159Z",
"product": 13
}
]
}
]
get a single image is like this
Alamofire.request(URL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: HEADER).responseJSON { (response) in
if response.result.error == nil {
guard let data = response.data else {return}
do {
if let json = try JSON(data: data).array {
for item in json {
let images = item["images"][0]["original"].stringValue
....
this returns only the indexed image.[0] if it is set to [1] it returns the indexed image at 1.
how do I return all the images so that I can loop through all and display in a collection view controller. more codes would be supplied on request.
You can dit it Like that :
if let json = try? JSON(data: data).arrayValue {
for item in json {
let imagesList = item["images"].arrayValue
let imagesURL = imagesList.map {$0["original"].string}.compactMap({$0})
if imagesURL.count > 0{
print( imagesURL[0])
}
}
}
Or:
do {
let json = try JSON(data: data).array
json?.forEach({ (item) in
let imagesList = item["images"].arrayValue
let imagesURL = imagesList.map {$0["original"].string}.compactMap({$0})
if imagesURL.count > 0{
print( imagesURL[0])
}
})
} catch {
print(error.localizedDescription)
}
I am getting a response from the server which contains show dates which I want to iterate how can I do that. The problem is that the key "instances" has a value of the object and that object contains the key value pair for the dates which I want to store. plz help
this is the JSON response:
{
"data": [
{
"id": "XYFYyvu2bckt",
"theater_id": "clzEVgztkcWB",
"theater_audi_id": "N9iDgooiCW6N",
"movie_lang_id": "B9x98d4IEpCt",
"booking_start_date": null,
"instances": {
"2018-04-18": [
{
"id": "vpcr2c9N12tL",
"show_time": "20:30:00"
}
],
"2018-04-19": [
{
"id": "X9kPcU7SLzrC",
"show_time": "20:30:00"
}
],
"2018-04-20": [
{
"id": "pFnFtXO5jKWp",
"show_time": "20:30:00"
}
],
"2018-04-21": [
{
"id": "hQuBFADUHeyS",
"show_time": "20:30:00"
}
],
"2018-04-22": [
{
"id": "vzXzOZvvKf9F",
"show_time": "20:30:00"
}
],
"2018-04-23": [
{
"id": "kAhzwyqoVGF4",
"show_time": "20:30:00"
}
],
"2018-04-24": [
{
"id": "wVXRjq6LrZJm",
"show_time": "20:30:00"
}
],
"2018-04-25": [
{
"id": "6hA1qglyP1Hf",
"show_time": "20:30:00"
}
],
"2018-04-26": [
{
"id": "NoLPN8RQNRXV",
"show_time": "20:30:00"
}
]
}
}
]
}
here is what i had tried:
_ = URLSession.shared.dataTask(with: request) { (Data, response, error) in
if Data != nil{
do{
let access = try JSONSerialization.jsonObject(with: Data!, options: []) as! [String:NSArray]
Completion(access)
for i in access["data"]!{
let a = i
let b = try JSONSerialization.data(withJSONObject: a as Any, options: .prettyPrinted)
let d = try JSONSerialization.jsonObject(with: b, options: []) as! [String: Any]
let e = d["instances"]
for (key, timeObj) in d["instances"]{
print(key)
}
}
}catch let e{
print(e)
}
}
}.resume()
You can try
let access = try JSONSerialization.jsonObject(with: Data!, options: []) as! [String:Any]
if let data = access["data"] as? [[String:Any]] , let instances = data[0]["instances"] as? [String:Any] {
print(instances)
}
Swift parsing desc and parsing selected element. I want to parse desc and after parsing desc parse desc content. thanks swift parsing desc and parsing selected element.
I have tried different methods. Does anyone have an idea on how we can make it possible? I tried the following code:
**Code for getting the data**
func demoApi1() {
Alamofire.request("", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
guard let json = response.result.value as! [[String:Any]]? else{ return}
print("Ang Response: , \(json)")
for item in json {
self.getAllDetail.append(item )
if let desc = item["dec"] as? String {
self.titleArray.append(desc)
print("motherfucker:" , self.titleArray)
}
}
if !self.getAllDetail.isEmpty{
DispatchQueue.main.async {
}
}
break
case .failure(_):
print("Error")
break
}
}
}
Response:
Ang Response [["status": {
name = ongoing;
}, "sched": 2018-04-10T14:22:00+08:00, "desc": asdasdasdsa, "id": 224, "reward": 1.00, "parent": das, "child": dasdas, "date_created": 2018-04-19T15:54:24.657644+08:00, "name": sad, "occurrence": {
name = once;
}, "type": , "date_modified": 2018-04-19T15:54:24.703520+08:00], ["status": {
name = ongoing;
}, "sched": 2018-04-19T15:54:24.657644+08:00, "desc": {
"questions" : [
{
"b" : 2,
"a" : 1
},
{
"b" : 3,
"a" : 2
},
{
"b" : 2,
"a" : 8
},
{
"b" : 9,
"a" : 7
},
{
"b" : 3,
"a" : 6
}
],
"operation" : "addition"
}, "id": 226, "reward": 1.00, "parent": shit, "child": , "date_created": 2018-04-23T14:16:35.739436+08:00, "name": chorename, "occurrence": {
name = once;
}, "type": homework, "date_modified": 2018-04-23T14:16:35.790237+08:00]]
String to Dictionary:
func stringToDictionary(_ strToJSON : String)-> [String:Any]{
print("JsonString:\(strToJSON)")
let data = strToJSON.data(using: .utf8)
var dict = [String:Any]()
do {
dict = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
return dict
}
catch let error as NSError {
print("Error is:\(error)")
}
return dict
}
Use it like this:
let dictConv = stringToDictionary("your_string")
print(dictConv)
I have a JSON data with structure and I don't know how to use for-loop with SwiftyJSON to get each sections entries of "path" and "updated" value. Anyone can help? Thanks.
var jsonData = "{
"css":[
{
"path": "style.css",
"updated": "12432"
},
{
"path": "base.css",
"updated": "34627"
},
],
"html":[
{
"path": "home.htm",
"updated": "3223"
},
{
"path": "about",
"updated": "3987"
}
]
}
"
I tried to code part of for-loop
let json = JSON(jsonData)
for ( ) in json {
let filepath =
let updated =
// do searching another json to found file exists and updates
}
It's on the README, under the section named "loop": https://github.com/SwiftyJSON/SwiftyJSON#loop
// If json is .Dictionary
for (key,subJson):(String, JSON) in json {
//Do something you want
}
// If json is .Array
// The `index` is 0..<json.count's string value
for (index,subJson):(String, JSON) in json {
//Do something you want
}
Applied to your specific JSON structure:
let jsonData = """
{
"css": [
{
"path": "style.css",
"updated": "12432"
},
{
"path": "base.css",
"updated": "34627"
}
],
"html": [
{
"path": "home.htm",
"updated": "3223"
},
{
"path": "about",
"updated": "3987"
}
]
}
""".data(using: .utf8)!
let json = JSON(data: jsonData)
for (_, subJson):(String, JSON) in json {
for (_, subJson):(String, JSON) in subJson {
let filepath = subJson["path"].stringValue
let updated = subJson["updated"].stringValue
print(filepath + " ~ " + updated)
}
}
Using Swift 4 Codable:
struct FileInfo: Decodable {
let path, updated: String
}
let dec = try! JSONDecoder().decode([String:[FileInfo]].self,from: jsonData)
print(dec)
As per your JSON structure, use this :
for (index,subJson):(String, JSON) in json {
print(index) // this prints "css" , "html"
for (key,subJson):(String, JSON) in subJson {
let filepath = subJson["path"]
let updated = subJson["updated"]
}
}