Related
I'm building a simple app which fetches json data from server and present it to user.I have a json file in vapor Public directory and when I try to parse it in iOS app it gives an error data is in incorrect format.I have converted the json file to swift struct by using json to swift online convertor.
But when I test the server response with postman it gives me the json file.In iOS app it gives me an error.I was able to fetch the data if I print it it gives 1372 bytes but when I try to parse it gives me an error that data is incorrect format
I'm getting following error
typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
my json file
{
"memes": [
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-53-300x300.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-53.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-1-300x210.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-1.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-54-300x250.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-54.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-55-300x269.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-55.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-56.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-56.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-57.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-57.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-58.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-58.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-8.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-8.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-59.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-59.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-66.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-66.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/download.jpg",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/download.jpg"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-12-300x281.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-12.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-13-300x281.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-13.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-14-240x300.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-14.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-61.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-61.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-62.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-62.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-17-300x300.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-17.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-18-252x300.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-18.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-19-300x281.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-19.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-20-249x300.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-20.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-21-300x233.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-21.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-63.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-63.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-64.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-64.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-24-300x150.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-24.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-25-289x300.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-25.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-27.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-27.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-52-300x300.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-52.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-30-300x221.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-30.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-65.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-65.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-32-300x239.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-32.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-33-300x181.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-33.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-34-300x300.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-34.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-35-300x250.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-35.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-36-300x269.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-36.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-37-300x210.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-37.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-38-300x292.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-38.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-39-300x167.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-39.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-40-249x300.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-40.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-41-300x294.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-41.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-42-300x295.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-42.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-43-234x300.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-43.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-44-300x263.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-44.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-45-300x255.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-45.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-46-300x300.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-46.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-47.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-47.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-48-300x210.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-48.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-49-249x300.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-49.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-50-300x300.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-50.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-51-300x146.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-51.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/05/python-2.jpg",
"url": "https://www.probytes.net/python-development-company/"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/1.jpg",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/1.jpg"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/2.jpg",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/2.jpg"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/3.jpg",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/3.jpg"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/4-1.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/4-1.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/5-1.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/5-1.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/6-1.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/6-1.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/7-1.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/7-1.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/8-1.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/8-1.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/9-1.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/9-1.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/10-1.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/10-1.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/11-1.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/11-1.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/12-1.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/12-1.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/13-1.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/13-1.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/14-1.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/14-1.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/15-1.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/15-1.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/16.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/16.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/17.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/17.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/18.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/18.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/19.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/19.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/20.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/20.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/9-1.jpg",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/9-1.jpg"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/8-1.jpg",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/8-1.jpg"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/7.jpg",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/7.jpg"
},
{
"image": "https://s.w.org/images/core/emoji/12.0.0-1/svg/1f609.svg"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/3-2.jpg",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/3-2.jpg"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/6-1.jpg",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/6-1.jpg"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/Imgur-8801b2-1.png",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/Imgur-8801b2-1.png"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/5-1.jpg",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/5-1.jpg"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/r_389776_tqMPa-1.jpg",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/r_389776_tqMPa-1.jpg"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/2-2.jpg",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/2-2.jpg"
},
{
"image": "https://www.probytes.net/wp-content/uploads/2018/01/4.jpg",
"url": "https://www.probytes.net/wp-content/uploads/2018/01/4.jpg"
}
]
}
Routes.swift file in Vapor
import Vapor
struct Welcome: Codable,Content {
let memes: [Meme]
}
struct Meme: Codable,Content {
let image: String
let url: String?
}
func routes(_ app: Application) throws {
var m = [Meme]()
var path = app.directory.publicDirectory
path.append("memes.json")
print(path)
guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else {return }
do
{
let memess = try JSONDecoder().decode(Welcome.self, from: data)
m = memess.memes
}
catch{
print(error.localizedDescription)
}
app.get { req in
return m
}
}
iOS App codable struct file
import Foundation
public struct Json4Swift_Base : Codable {
public let memes : [Memes]?
public enum CodingKeys: String, CodingKey {
case memes = "memes"
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
memes = try values.decodeIfPresent([Memes].self, forKey: .memes)
}
}
public struct Memes : Codable {
public let image : String?
public let url : String?
public enum CodingKeys: String, CodingKey {
case image = "image"
case url = "url"
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
image = try values.decodeIfPresent(String.self, forKey: .image)
url = try values.decodeIfPresent(String.self, forKey: .url)
}
}
NetworkService file
import Foundation
public class NetworkService
{
public static let sharedobj = NetworkService()
public let url = URL(string:"http://127.0.0.1:8080")
public let session = URLSession(configuration: .default)
public func getMemes(onSucces:#escaping([Memes],Error?)->Void)
{
let task = session.dataTask(with: url!) { (data, response, error) in
do
{
let items = try JSONDecoder().decode(Json4Swift_Base.self, from: data!)
onSucces(items.memes!,error)
}
catch
{
print(error.localizedDescription)
}
}
task.resume()
}
}
In your Vapor code you decode the file and then extract only the array to a property so assuming that this is what you encode and send to the client then you only receive the array.
Like this
"[
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-53-300x300.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-53.png"
},
{
"image": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-1-300x210.png",
"url": "https://www.testbytes.net/wp-content/uploads/2019/06/Untitled-1.png"
},
...
]"
So in your client you should decode the array only
let items = try JSONDecoder().decode([Memes].self, from: data!)
And you don't need init(from:) or a CodingKey enum here.
I have problem with parse json to collectionview
That is my JSON:
{
"statusCode": 200,
"message": "Список курсов",
"content": [
{
"id": 1,
"slug": "kurs-a1",
"title": "Курс А1",
"can_access": 1,
"passed": 1,
"sections": [
{
"id": 1,
"slug": "razdel-1",
"title": "Раздел 1",
"can_access": 1,
"passed": 1,
"lessons": [
{
"id": 1,
"position": 1,
"title": "Сәлемдесу",
"slug": "salemdesu",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 1,
"passed": 1
},
{
"id": 3,
"position": 2,
"title": "Танысу",
"slug": "tanysu",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 1,
"passed": 1
}
]
},
{
"id": 2,
"slug": "razdel-2",
"title": "Раздел 2",
"can_access": 1,
"passed": 0,
"lessons": [
{
"id": 4,
"position": 3,
"title": "Бұл – менің отбасым",
"slug": "bul-menin-otbasym",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 1,
"passed": 0
},
{
"id": 5,
"position": 4,
"title": "Жасы нешеде?",
"slug": "zhasy-neshede",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 1,
"passed": 0
}
]
},
{
"id": 3,
"slug": "razdel-3",
"title": "Раздел 3",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 7,
"position": 5,
"title": "Туған күн",
"slug": "tugan-kun",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 9,
"position": 6,
"title": "Құттықтау",
"slug": "kuttyktau",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 4,
"slug": "razdel-4",
"title": "Раздел 4",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 10,
"position": 7,
"title": "Адам келбеті",
"slug": "adam-kelbeti",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 12,
"position": 8,
"title": "Адамның мінез-құлқы",
"slug": "adamnyn-minez-kulky",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 5,
"slug": "razdel-5",
"title": "Раздел 5",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 13,
"position": 9,
"title": "Менің мамандығым",
"slug": "menin-mamandygym",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 15,
"position": 10,
"title": "Кім болып жұмыс істейді?",
"slug": "kim-bolyp-zhumys-istejdi",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 6,
"slug": "razdel-6",
"title": "Раздел 6",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 16,
"position": 11,
"title": "Жұмыс орны",
"slug": "zhumys-orny",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 17,
"position": 12,
"title": "Жұмыс күні",
"slug": "zhumys-kuni",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 7,
"slug": "razdel-7",
"title": "Раздел 7",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 19,
"position": 13,
"title": "Тесты ЦОР-а",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 20,
"position": 14,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 8,
"slug": "razdel-8",
"title": "Раздел 8",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 22,
"position": 15,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 23,
"position": 16,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 9,
"slug": "razdel-9",
"title": "Раздел 9",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 25,
"position": 17,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 27,
"position": 18,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 10,
"slug": "razdel-10",
"title": "Раздел 10",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 28,
"position": 19,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 29,
"position": 20,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 11,
"slug": "razdel-11",
"title": "Раздел 11",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 32,
"position": 21,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 33,
"position": 22,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 12,
"slug": "razdel-12",
"title": "Раздел 12",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 34,
"position": 23,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 35,
"position": 24,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
}
]
}
]
}
I decode it and i want parse it to collectionview.
How can i get content [{sections[{lessons[{title}]}]}]?
I made a request
func numberOfSections(in collectionView: UICollectionView) -> Int {
return arrData1.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let dn = arrData1[section]
let st = dn.sections?[section]
return (st?.lessons?.count)!
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "main_cell", for: indexPath) as! MainCollectionViewCell
cell.lesson_text_1.text = arrData1.first?.sections?[indexPath.item].title
// cell.lesson_img_1.image = UIImage(named: lesson_image_1[indexPath.row])
// cell.lesson_text_1.text = lesson_text_1[indexPath.row]
return cell
}
but it return 2 cell to me
But i need 24 lessons!
Thank you
Decoding
struct Welcome: Codable {
let statusCode: Int
let message: String
let content: [Content]
}
struct Content: Codable {
let id: Int
let slug, title: String
let canAccess: Int?
let passed: Int
let sections: [Content]?
let lessons: [Lesson]?
enum CodingKeys: String, CodingKey {
case id, slug, title
case canAccess = "can_access"
case passed, sections
case lessons = "lessons"
}
}
struct Lesson: Codable {
let id, position: Int
let title, slug: String
let image: String
let canAccess: Int?
let passed: Int
enum CodingKeys: String, CodingKey {
case id, position, title, slug, image
case canAccess = "can_access"
case passed
}
}
api call function
let mData = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let data_new = try decoder.decode(Welcome.self, from: data)
DispatchQueue.main.async {
self.tableview.reloadData()
self.arrData1 = data_new.content
print(data_new)
}
} catch {
print("Error in CheckNew is : \n\(error)")
}
}
mData.resume()
enter image description here
Although the JSON structure is quite similar I recommend to use separate structs for Section and Lesson.
Another benefit is you get rid of all optionals
struct Welcome: Codable {
let statusCode: Int
let message: String
let content: [Content]
}
struct Content: Codable {
let id: Int
let slug, title: String
let canAccess: Int
let passed: Int
let sections: [Section]
}
struct Section: Codable {
let id: Int
let title, slug: String
let canAccess: Int
let passed: Int
let lessons: [Lesson]
}
struct Lesson: Codable {
let id, position: Int
let title, slug: String
let image: URL
let canAccess: Int
let passed: Int
}
As you are using the .convertFromSnakeCase strategy all coding keys are redundant.
I have api it returns json response(https://pixabay.com/api/?key=10961259-e4e939648ed5abb6879f1fbbc&q=yellow+flowers&image_type=photo)
I want to access parameters(webformatURL, tags) from the response. I made URL session request and getting data is like below. How can i query and access those parameters from the response in swift. I'm new to programming please suggest me in swift.
//Mark:- Method to fetch data from the url
func getDataFromUrl(){
let url = URL(string: "https://pixabay.com/api/?key=10961259-e4e939648ed5abb6879f1fbbc&q=yellow+flowers&image_type=photo")
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "GET"
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if error == nil
{
do
{
let respDict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
print("Some Data: \(respDict)")
}
catch let error2 as NSError
{
print(error2)
}
}
})
dataTask.resume()
}
And the response is:
{
"totalHits": 500,
"hits": [
{
"largeImageURL": "https://pixabay.com/get/ea35b70c2afc053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 848,
"imageWidth": 6000,
"id": 3063284,
"user_id": 1564471,
"views": 476351,
"comments": 191,
"pageURL": "https://pixabay.com/en/rose-flower-petal-floral-noble-3063284/",
"imageHeight": 4000,
"webformatURL": "https://pixabay.com/get/ea35b70c2afc053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "rose, flower, petal",
"downloads": 288342,
"user": "annca",
"favorites": 720,
"imageSize": 3574625,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2015/11/27/06-58-54-609_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2018/01/05/16/24/rose-3063284_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ea34b00c2bf5093ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 706,
"imageWidth": 2736,
"id": 3113318,
"user_id": 7410713,
"views": 342627,
"comments": 113,
"pageURL": "https://pixabay.com/en/sunflower-nature-flora-flower-3113318/",
"imageHeight": 1824,
"webformatURL": "https://pixabay.com/get/ea34b00c2bf5093ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "sunflower, nature, flora",
"downloads": 242156,
"user": "bichnguyenvo",
"favorites": 454,
"imageSize": 1026006,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2017/12/16/10-28-39-199_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2018/01/28/11/24/sunflower-3113318_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ea37b80d21f7033ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 400,
"webformatWidth": 640,
"likes": 434,
"imageWidth": 3200,
"id": 3292932,
"user_id": 2216431,
"views": 184738,
"comments": 34,
"pageURL": "https://pixabay.com/en/sunflower-vase-vintage-retro-wall-3292932/",
"imageHeight": 2000,
"webformatURL": "https://pixabay.com/get/ea37b80d21f7033ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 93,
"tags": "sunflower, vase, vintage",
"downloads": 146666,
"user": "Yuri_B",
"favorites": 593,
"imageSize": 2563708,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/01/15/10-52-15-382_250x250.png",
"previewURL": "https://cdn.pixabay.com/photo/2018/04/05/14/09/sun-flower-3292932_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/eb37b80a2cf7053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 486,
"imageWidth": 5363,
"id": 2295434,
"user_id": 334088,
"views": 54291,
"comments": 33,
"pageURL": "https://pixabay.com/en/spring-bird-bird-tit-spring-blue-2295434/",
"imageHeight": 3575,
"webformatURL": "https://pixabay.com/get/eb37b80a2cf7053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "spring bird, bird, tit",
"downloads": 25018,
"user": "jill111",
"favorites": 548,
"imageSize": 2938651,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/06/27/01-23-02-27_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2017/05/08/13/15/spring-bird-2295434_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ee34b40a2cf41c22d2524518b74d469fe576e0d010ac104491f4c47aaeeeb5bf_1280.jpg",
"webformatHeight": 360,
"webformatWidth": 640,
"likes": 258,
"imageWidth": 3020,
"id": 715540,
"user_id": 916237,
"views": 82194,
"comments": 31,
"pageURL": "https://pixabay.com/en/yellow-natural-flower-blossom-715540/",
"imageHeight": 1703,
"webformatURL": "https://pixabay.com/get/ee34b40a2cf41c22d2524518b74d469fe576e0d010ac104491f4c47aaeeeb5bf_640.jpg",
"type": "photo",
"previewHeight": 84,
"tags": "yellow, natural, flower",
"downloads": 39827,
"user": "Wow_Pho",
"favorites": 256,
"imageSize": 974940,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2015/04/07/14-10-15-590_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2015/04/10/00/41/yellow-715540_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ea37b00a29fc093ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 358,
"webformatWidth": 640,
"likes": 336,
"imageWidth": 2027,
"id": 3215188,
"user_id": 7097598,
"views": 135865,
"comments": 94,
"pageURL": "https://pixabay.com/en/flowers-orange-orange-petals-3215188/",
"imageHeight": 1134,
"webformatURL": "https://pixabay.com/get/ea37b00a29fc093ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 83,
"tags": "flowers, orange, orange petals",
"downloads": 93385,
"user": "Candiix",
"favorites": 274,
"imageSize": 399066,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2017/12/06/20-08-45-84_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2018/03/10/20/26/flowers-3215188_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/e830b20928fc093ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 419,
"webformatWidth": 640,
"likes": 235,
"imageWidth": 4896,
"id": 1536088,
"user_id": 1195798,
"views": 268764,
"comments": 53,
"pageURL": "https://pixabay.com/en/sunflower-flower-bloom-yellow-1536088/",
"imageHeight": 3208,
"webformatURL": "https://pixabay.com/get/e830b20928fc093ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 98,
"tags": "sunflower, flower, bloom",
"downloads": 40996,
"user": "Couleur",
"favorites": 203,
"imageSize": 5103399,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/09/29/00-20-33-645_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2016/07/23/00/12/sun-flower-1536088_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/eb34b50a2df7083ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 390,
"webformatWidth": 640,
"likes": 306,
"imageWidth": 4000,
"id": 2145539,
"user_id": 2364555,
"views": 36019,
"comments": 27,
"pageURL": "https://pixabay.com/en/crocus-flower-wet-spring-2145539/",
"imageHeight": 2443,
"webformatURL": "https://pixabay.com/get/eb34b50a2df7083ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 91,
"tags": "crocus, flower, wet",
"downloads": 20750,
"user": "pixel2013",
"favorites": 286,
"imageSize": 823922,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/02/25/16-46-24-974_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2017/03/15/09/00/crocus-2145539_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ec33b50e2ce90021d85a5854e74c4f90e275e7dc04b0144591f5c270a4edb2_1280.jpg",
"webformatHeight": 428,
"webformatWidth": 640,
"likes": 436,
"imageWidth": 3872,
"id": 56414,
"user_id": 9003,
"views": 57529,
"comments": 75,
"pageURL": "https://pixabay.com/en/anemone-flower-blossom-bloom-blue-56414/",
"imageHeight": 2592,
"webformatURL": "https://pixabay.com/get/ec33b50e2ce90021d85a5854e74c4f90e275e7dc04b0144591f5c270a4edb2_640.jpg",
"type": "photo",
"previewHeight": 100,
"tags": "anemone, flower, blossom",
"downloads": 20907,
"user": "Albenheim",
"favorites": 364,
"imageSize": 770723,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2012/09/08/21-14-56-990_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2012/09/08/21/51/anemone-56414_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/e830b00d20f5023ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 323,
"webformatWidth": 640,
"likes": 211,
"imageWidth": 3861,
"id": 1512813,
"user_id": 2364555,
"views": 63538,
"comments": 22,
"pageURL": "https://pixabay.com/en/lily-flowers-early-flower-garden-1512813/",
"imageHeight": 1952,
"webformatURL": "https://pixabay.com/get/e830b00d20f5023ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 75,
"tags": "lily, flowers, early",
"downloads": 31782,
"user": "pixel2013",
"favorites": 209,
"imageSize": 1037708,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/02/25/16-46-24-974_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2016/07/12/18/54/lily-1512813_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ee37b80a29f11c22d2524518b74d469fe576e0d010ac104491f4c47aaeeeb5bf_1280.jpg",
"webformatHeight": 416,
"webformatWidth": 640,
"likes": 269,
"imageWidth": 1980,
"id": 729515,
"user_id": 909086,
"views": 33664,
"comments": 17,
"pageURL": "https://pixabay.com/en/flower-beautiful-bloom-blooming-729515/",
"imageHeight": 1288,
"webformatURL": "https://pixabay.com/get/ee37b80a29f11c22d2524518b74d469fe576e0d010ac104491f4c47aaeeeb5bf_640.jpg",
"type": "photo",
"previewHeight": 97,
"tags": "flower, beautiful, bloom",
"downloads": 21810,
"user": "Bess-Hamiti",
"favorites": 348,
"imageSize": 370390,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2017/09/19/10-02-47-777_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2015/04/19/08/33/flower-729515_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/e83cb60d2cf5003ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 372,
"webformatWidth": 640,
"likes": 247,
"imageWidth": 4288,
"id": 1972411,
"user_id": 1777190,
"views": 84036,
"comments": 29,
"pageURL": "https://pixabay.com/en/drip-blossom-bloom-yellow-1972411/",
"imageHeight": 2499,
"webformatURL": "https://pixabay.com/get/e83cb60d2cf5003ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 87,
"tags": "drip, blossom, bloom",
"downloads": 71846,
"user": "susannp4",
"favorites": 244,
"imageSize": 1510459,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2015/12/16/17-56-55-832_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2017/01/11/17/27/drip-1972411_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/e834b30829f3053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 338,
"imageWidth": 4752,
"id": 1127174,
"user_id": 1445608,
"views": 93274,
"comments": 24,
"pageURL": "https://pixabay.com/en/sunflower-summer-yellow-nature-1127174/",
"imageHeight": 3168,
"webformatURL": "https://pixabay.com/get/e834b30829f3053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "sunflower, summer, yellow",
"downloads": 55774,
"user": "mploscar",
"favorites": 341,
"imageSize": 3922163,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2016/01/05/14-08-20-943_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2016/01/08/05/24/sunflower-1127174_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/e834b2082bf11c22d2524518b74d469fe576e0d010ac104491f4c47aaeeeb5bf_1280.jpg",
"webformatHeight": 355,
"webformatWidth": 640,
"likes": 167,
"imageWidth": 2410,
"id": 113735,
"user_id": 817,
"views": 91032,
"comments": 29,
"pageURL": "https://pixabay.com/en/rose-flower-yellow-yellow-rose-113735/",
"imageHeight": 1337,
"webformatURL": "https://pixabay.com/get/e834b2082bf11c22d2524518b74d469fe576e0d010ac104491f4c47aaeeeb5bf_640.jpg",
"type": "photo",
"previewHeight": 83,
"tags": "rose, flower, yellow",
"downloads": 13679,
"user": "blizniak",
"favorites": 152,
"imageSize": 299425,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2013/06/28/17-07-05-714_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2013/05/26/12/14/rose-113735_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/e836b00629f5053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 249,
"imageWidth": 4272,
"id": 1319114,
"user_id": 485024,
"views": 87475,
"comments": 24,
"pageURL": "https://pixabay.com/en/girl-flowers-yellow-beauty-nature-1319114/",
"imageHeight": 2848,
"webformatURL": "https://pixabay.com/get/e836b00629f5053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "girl, flowers, yellow",
"downloads": 41303,
"user": "AdinaVoicu",
"favorites": 263,
"imageSize": 3837334,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/12/07/21-49-54-663_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2016/04/09/23/10/girl-1319114_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ea32b30f2bfc023ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 108,
"imageWidth": 6000,
"id": 3720383,
"user_id": 6246704,
"views": 16075,
"comments": 32,
"pageURL": "https://pixabay.com/en/flower-g%C3%A9rbel-yellow-flower-flower-3720383/",
"imageHeight": 4000,
"webformatURL": "https://pixabay.com/get/ea32b30f2bfc023ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "flower gérbel, yellow flower, flower",
"downloads": 9864,
"user": "fernandozhiminaicela",
"favorites": 81,
"imageSize": 2117262,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/06/04/17-13-01-772_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2018/10/03/03/42/flower-gerbel-3720383_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ea35b40f28f3073ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 285,
"imageWidth": 5472,
"id": 3050076,
"user_id": 6663646,
"views": 131773,
"comments": 28,
"pageURL": "https://pixabay.com/en/portrait-girl-fog-flowers-beauty-3050076/",
"imageHeight": 3648,
"webformatURL": "https://pixabay.com/get/ea35b40f28f3073ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "portrait, girl, fog",
"downloads": 92671,
"user": "ThuyHaBich",
"favorites": 283,
"imageSize": 2914111,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2017/11/17/08-35-57-188_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2017/12/30/13/25/portrait-3050076_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ec37b20a20e90021d85a5854e74c4f90e275e7dc04b0144591f5c270a4edb2_1280.jpg",
"webformatHeight": 360,
"webformatWidth": 640,
"likes": 179,
"imageWidth": 1920,
"id": 52358,
"user_id": 5783,
"views": 28923,
"comments": 20,
"pageURL": "https://pixabay.com/en/flower-wild-flower-nature-52358/",
"imageHeight": 1080,
"webformatURL": "https://pixabay.com/get/ec37b20a20e90021d85a5854e74c4f90e275e7dc04b0144591f5c270a4edb2_640.jpg",
"type": "photo",
"previewHeight": 84,
"tags": "flower, wild flower, nature",
"downloads": 10460,
"user": "PeterDargatz",
"favorites": 154,
"imageSize": 172383,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2012/06/22/22-42-41-494_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2012/07/12/14/50/flower-52358_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/eb31b10b2ff2083ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 427,
"webformatWidth": 640,
"likes": 204,
"imageWidth": 6016,
"id": 2404769,
"user_id": 4331363,
"views": 29872,
"comments": 21,
"pageURL": "https://pixabay.com/en/summer-field-nature-cereals-2404769/",
"imageHeight": 4016,
"webformatURL": "https://pixabay.com/get/eb31b10b2ff2083ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 100,
"tags": "summer, field, nature",
"downloads": 12788,
"user": "geraldfriedrich2",
"favorites": 257,
"imageSize": 4290219,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2017/02/22/12-32-00-453_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2017/06/15/10/25/summer-2404769_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ea33b50f21f7043ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 213,
"imageWidth": 5574,
"id": 3640935,
"user_id": 334088,
"views": 103667,
"comments": 54,
"pageURL": "https://pixabay.com/en/sunflowers-field-woman-yellow-3640935/",
"imageHeight": 3717,
"webformatURL": "https://pixabay.com/get/ea33b50f21f7043ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "sunflowers, field, woman",
"downloads": 86701,
"user": "jill111",
"favorites": 186,
"imageSize": 4970597,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/06/27/01-23-02-27_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2018/08/29/22/52/sunflowers-3640935_150.jpg"
}
],
"total": 17148
}
You are getting one JSON object with keys:
totalHits
hits
total
In the above three keys, value of https is another JSON array having many json objects inside it. you can get that object by
let respDict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:Any]
let httpDictArray = respDict["hits"] as! [Any]
for dictionary in httpDictArray{
if let dict = dictionary as? [String:Any]
{
let webFormatUrl = dict["webformatURL"] as! String
let tags = dict["tags"] as! String
}
}
Here tags is a string which is a concatenation of many words separated by comma.
so from tags string you can get the array of tags as
let tagArray = tags.components(separatedBy: ", ")
The Decodable protocol is the most convenient way to parse JSON in Swift 4+
struct Root : Decodable {
let totalHits : Int
let hits : [Hit]
}
struct Hit : Decodable {
let webformatURL : URL
let tags : String
}
func getDataFromUrl() {
let url = URL(string: "https://pixabay.com/api/?key=10961259-e4e939648ed5abb6879f1fbbc&q=yellow+flowers&image_type=photo")
let session = URLSession.shared
let dataTask = session.dataTask(with: url!) { data, response, error in
guard let data = data else { print(error!); return }
do {
let result = try JSONDecoder().decode(Root.self, from: data)
let hits = result.hits
for hit in hits {
print("webformatURL: ", hit.webformatURL, "tags:", hit.tags)
}
} catch {
print(error)
}
}
dataTask.resume()
}
getDataFromUrl()
Note:
An URLRequest is not needed in this case and don't use NSMutableURLRequest in Swift anyway.
Now that you have your response in a dictionary, you can do the following to get the hits:
guard let results = respDict as? [String: Any],
let hits = results["hits"] as? Array<[String:Any]> else {
return
}
Now, when you have the hits, let's transform this array of objects into two array. array of urls, and array of tags.
let urls = hits.flatMap { $0["webformatURL"] as? String }
let tags = hits.flatMap { $0["tags"] as? String }
There you go!
Here is the simple approach,
struct HitResponse: Codable {
var total: Int
var totalHits: Int
var hits: [HitObject]
}
struct HitObject: Codable {
var largeImageURL: String
var webformatHeight: Int
var webformatWidth: Int
var likes: Int
var imageWidth: Int
var id: Int
var user_id: Int
var views: Int
var comments: Int
var pageURL: String
var imageHeight: Int
var webformatURL: String
var type: String
var previewHeight: Int
var tags: String
var downloads: Int
var user: String
var favorites: Int
var imageSize: Int
var previewWidth: Int
var userImageURL: String
var previewURL: String
}
enum APIResponse {
case success(result: Result)
case error(error: Error)
}
struct Result{
var object: Any
}
class APIRequester {
static func request(for url: URL, completionHandler: #escaping (_ response: APIResponse)->Void) {
let sesseion = URLSession.shared
let task = sesseion.dataTask(with: url) { (data, urlResponse, error) in
// data mapping to model
if let lData = data {
do {
let decode = try JSONDecoder().decode(HitResponse.self, from: lData)
let responseMap: APIResponse = .success(result: Result(object: decode))
completionHandler(responseMap)
}catch let mappingError {
let responseMap: APIResponse = .error(error: mappingError)
completionHandler(responseMap)
}
}
//fall back original error
let responseMap: APIResponse = .error(error: error!)
completionHandler(responseMap)
}
task.resume()
}
}
// Usage
let url = URL(string: "https://pixabay.com/api/?key=10961259-e4e939648ed5abb6879f1fbbc&q=yellow+flowers&image_type=photo")
APIRequester.request(for: url!) { (response) in
switch response {
case .success(let result):
if let hitResponse = result.object as? HitResponse {
for hit in hitResponse.hits {
//the final output
print(hit.tags)
print(hit.webformatURL)
print("\n")
}
}
case .error(let error):
// handle error
print("error \(error)")
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
{
"status": "true",
"message": "11 records found",
"response": [
{
"name": "1",
"address": "565400-",
"phone": "",
"gym_email": "",
"images": ""
},
{
"name": "123",
"address": "102-",
"phone": "",
"gym_email": "1#2.com",
"images": ""
},
{
"name": "Burn Gym & Spa",
"address": "Sector 11,HaryanaPanchkula-134101",
"phone": "",
"gym_email": "1#2.com",
"images": "a:1:{i:0;s:18:\"1478177269200.jpeg\";}"
},
{
"name": "Burn Gym",
"address": "NAC,ManimajraChandigarhPanchkula-134112",
"phone": "",
"gym_email": null,
"images": ""
},
{
"name": "Burn Gym & Spa",
"address": "Sector 11,ChandigarhAmbala-160101",
"phone": "585888",
"gym_email": "1#2.com",
"images": ""
},
{
"name": "test gym",
"address": "Sector 11,HaryanaPanchkula-134101",
"phone": "0",
"gym_email": "1#2.com",
"images": "a:1:{i:1;s:17:\"1478579644341.png\";}"
},
{
"name": "test gym",
"address": "Sector 12HaryanaPanchkula-134101",
"phone": "0",
"gym_email": "",
"images": ""
},
{
"name": "new gym",
"address": "sector 11HaryanaPanchkula-134112",
"phone": "789654123",
"gym_email": "keshavkpnf#gmail.com",
"images": ""
},
{
"name": "hrhrrth",
"address": "sector 11HaryanaPanchkula-134101",
"phone": "8054233444",
"gym_email": "keshavkpnf#gmail.com",
"images": ""
},
{
"name": "hrhrrth",
"address": "sector 4HaryanaPanchkula-134101",
"phone": "0",
"gym_email": "",
"images": ""
},
{
"name": "hrhrrth",
"address": "sector 11HaryanaPanchkula-134101",
"phone": "8054233444",
"gym_email": "keshavkpnf#gmail.com",
"images": ""
}
]
}
You can get the value of address as:
guard let response = json["response"] as? [[String:AnyObject]] else {
print("Nothing here")
return
}
then you can get address from the response array by looping,
for data in response {
print(data["address"] as? String)
}
if((jsonResult) != nil) {
let swiftyJsonVar = jsonResult!
do {
if let dicObj = swiftyJsonVar as? NSDictionary {
print("Response is dictionary")
print(dicObj)
let arrObj = dicObj["response"] as NSArray
// Then iterate your arrObj and do as per your need.
//for eg.
arrObj[0]["address"]
}
}
}
addressLabel.text=[[[mdict objectForKey:#"response"]objectAtIndex:indexPath.row]valueForKey:#"address"];
I have this kind of documents in a MongoDb collection:
[
{
"_id": {
"id": 892,
"answer": "C",
"level": "regular"
},
"total": 4
},
{
"_id": {
"id": 891,
"answer": "Regular",
"level": "neutral"
},
"total": 3
},
{
"_id": {
"id": 892,
"answer": "B",
"level": "regular"
},
"total": 3
},
{
"_id": {
"id": 891,
"answer": "Ótimo",
"level": "positive"
},
"total": 5
},
{
"_id": {
"id": 892,
"answer": "E",
"level": "regular"
},
"total": 3
},
{
"_id": {
"id": 891,
"answer": "Bom",
"level": "positive"
},
"total": 1
},
{
"_id": {
"id": 891,
"answer": "Ruim",
"level": "negative"
},
"total": 2
},
{
"_id": {
"id": 892,
"answer": "D",
"level": "regular"
},
"total": 3
},
{
"_id": {
"id": 891,
"answer": "Péssimo",
"level": "negative"
},
"total": 3
},
{
"_id": {
"id": 892,
"answer": "F",
"level": "regular"
},
"total": 1
}
]
I'm trying to count answer and level ocurrences using MongoDb aggregation pipiline. I'm expecting some output like this:
[
{
"id": 891,
"answers": [
{
"answer": "Ótimo",
"count": 5
},
{
"answer": "Bom",
"count": 1
},
{
"answer": "Regular",
"count": 3
},
{
"answer": "Ruim",
"count": 2
},
{
"answer": "Péssimo",
"count": 3
}
],
"levels": [
{
"level": "positive",
"count": 6
},
{
"level": "neutral",
"count": 3
},
{
"level": "negative",
"count": 5
}
],
"total": 14
},
{
"id": 892,
"answers": [
{
"answer": "B",
"count": 3
},
{
"answer": "C",
"count": 4
},
{
"answer": "D",
"count": 3
},
{
"answer": "E",
"count": 3
},
{
"answer": "F",
"count": 1
},
],
"levels": [
{
"level": "regular",
"count": 14
}
],
"total": 14
}
]
How could I achieve the desired output using MongoDb aggregation pipeline?
EDIT: Actually I'm already using $group to achieve something like that, but I guess only one $group step on the pipeline will not achieve the desired output. Here is my current $group step:
{
$group: {
_id: {
id: "$_id.id"
},
answers: {
$push: {
answer: "$_id.answer",
count: "$count"
}
},
levels: {
$push: {
level: "$_id.level",
count: "$count"
}
},
total: { $sum: "$count" }
}
}
Here is the output I have so far:
[
{
"_id": {
"id": 892
},
"answers": [
{
"answer": "F",
"count": 1
},
{
"answer": "D",
"count": 3
},
{
"answer": "E",
"count": 3
},
{
"answer": "C",
"count": 4
},
{
"answer": "B",
"count": 3
}
],
"levels": [
{
"level": "regular"
},
{
"level": "regular"
},
{
"level": "regular"
},
{
"level": "regular"
},
{
"level": "regular"
}
]
},
{
"_id": {
"id": 891
},
"answers": [
{
"answer": "Ruim",
"count": 2
},
{
"answer": "Péssimo",
"count": 3
},
{
"answer": "Bom",
"count": 1
},
{
"answer": "Regular",
"count": 3
},
{
"answer": "Ótimo",
"count": 5
}
],
"levels": [
{
"level": "negative"
},
{
"level": "negative"
},
{
"level": "positive"
},
{
"level": "neutral"
},
{
"level": "positive"
}
]
}
]
The following aggregation pipeline:
{ $group: {
_id: { id: "$_id.id" },
answers: {
$push: {
answer: "$_id.answer",
level: "$_id.level",
count: "$total"
}
},
levels: {
$push: {
level: "$_id.level",
count: "$total"
}
}
}},
{ $unwind: $levels },
{ $group: {
_id: {
id: "$_id.id",
level: "$levels.level"
},
answers: { $addToSet: "$answers" },
total: { $sum: "$levels.count" }
}},
{ $group: {
_id: { id: "$_id.id" },
answers: { $addToSet: "$answers" },
levels: {
$push: {
level: "$_id.level",
count: "$total"
}
},
total: { $sum: "$total" }
}},
{ $project: {
_id: 0,
id: "$_id.id",
answers: 1,
levels: 1,
total: 1
}}
Will produce the desired output.