Swift: Parse data Codable protocol not working - json

I have a link that returns a json file, I try to print the data but it does not work it is always nil, here is the link:
http://heroapps.co.il/employee-tests/ios/logan.json
And my code:
struct DataClass: Codable {
let name: String?
let nickname: String?
let image: URL?
let dateOfBirth: Int?
let powers: [String]?
let actorName: String?
let movies: [Movie]?
enum CodingKeys: String, CodingKey {
case name = "name"
case nickname = "nickname"
case image = "image"
case dateOfBirth = "dateOfBirth"
case powers = "powers"
case actorName = "actorName"
case movies = "movies"
}
}
struct Movie: Codable {
let name: String?
let year: Int?
enum CodingKeys: String, CodingKey {
case name = "name"
case year = "year"
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
guard let gitUrl = URL(string: "http://heroapps.co.il/employee-tests/ios/logan.json") else { return }
URLSession.shared.dataTask(with: gitUrl) { (data, response, error) in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
let gitData = try decoder.decode(Movie.self, from: data)
print(gitData.name ?? "") //Print nil
} catch let err {
print("Err", err)
}
}.resume()
}
Thank you for helping me find where my error comes from, this is the first time I use this method to retrieve JSON data

You are not parsing the top level of the JSON. (success, errorCode, message and data).
Playground code for testing...
import Foundation
let jsonData = """
{
"success": true,
"errorCode": 0,
"message": "Succcess",
"data": {
"name": "Logan Howlett",
"nickname": "The Wolverine",
"image": "http://heroapps.co.il/employee-tests/ios/logan.jpg",
"dateOfBirth": 1880,
"powers": [
"Adamantium Bones",
"Self-Healing",
"Adamantium Claws"
],
"actorName": "Hugh Jackman",
"movies": [
{
"name": "X-Men Origins: Wolverine",
"year": 2009
},
{
"name": "The Wolverine",
"year": 2013
},
{
"name": "X-Men: Days of Future Past",
"year": 2014
},
{
"name": "Logan",
"year": 2017
}
]
}
}
""".data(using: .utf8)!
struct JSONResponse: Codable {
let success: Bool
let errorCode: Int
let message: String
let data: DataClass
}
struct DataClass: Codable {
let name: String?
let nickname: String?
let image: URL?
let dateOfBirth: Int?
let powers: [String]?
let actorName: String?
let movies: [Movie]?
enum CodingKeys: String, CodingKey {
case name = "name"
case nickname = "nickname"
case image = "image"
case dateOfBirth = "dateOfBirth"
case powers = "powers"
case actorName = "actorName"
case movies = "movies"
}
}
struct Movie: Codable {
let name: String?
let year: Int?
enum CodingKeys: String, CodingKey {
case name = "name"
case year = "year"
}
}
do {
let result = try JSONDecoder().decode(JSONResponse.self, from: jsonData)
print(result)
} catch {
print(error)
}

Related

SwiftUI - Decoding a JSON returns blank screen

I am trying to decode a JSON object from a remote API, Xcode doesn't raise any flags but the screen remains blank, I couldn't pinpoint where the error is coming from but if I have to take I guess, I think it's something to do with my parsing.
What's going wrong here? everything seems at its place
This is my ContentView.swift
import SwiftUI
struct ContentView: View {
#State var results = UserProducts(status: Bool(), userProducts: [UserProduct]())
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: nil) {
ForEach(0..<results.userProducts!.count) {
res in
VStack(){Text(verbatim: String(format: String(),((results.userProducts![res].id ?? "NA"))))}
}.onAppear(perform: loadShelf)
}
}
Spacer()
}).background(Color(red: 250 / 255, green: 248 / 255, blue: 244 / 255))
}
func loadShelf(){
guard let apiBaseURL = URL(string: "...") else {
print("Base URL is invalid.")
return
}
let request = URLRequest(url: apiBaseURL)
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async {
if let data = data {
do{
let decoded = try JSONDecoder().decode(UserProducts.self, from: data)
self.results = decoded
print("decoded: \(decoded)")
//prints: UserProducts(status: nil, userProducts: nil, recommendedProducts: nil)
}
catch{
print("Fetching data failed: \(error)")
}
}
}
}.resume()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
This is my Structs:
import Foundation
// MARK: - UserProducts
struct UserProducts: Codable {
let status: Bool?
let userProducts: [UserProduct]?
enum CodingKeys: String, CodingKey {
case status
case userProducts = "user_products"
}
}
// MARK: - UserProduct
struct UserProduct: Codable {
let id, userID, productID: Int?
let routineTime, createdAt, updatedAt: String?
let archived, volume: Int?
let deletedAt, addedBy, weeklyRoutineOne, weeklyRoutineTwo: String?
let product: Product?
let user: User?
let phaseOut, refill, empty, recommended: Int?
enum CodingKeys: String, CodingKey {
case id
case userID = "user_id"
case productID = "product_id"
case routineTime = "routine_time"
case createdAt = "created_at"
case updatedAt = "updated_at"
case archived, volume
case deletedAt = "deleted_at"
case addedBy = "added_by"
case weeklyRoutineOne = "weekly_routine_one"
case weeklyRoutineTwo = "weekly_routine_two"
case product, user
case phaseOut = "phase_out"
case refill, empty, recommended
}
}
// MARK: - Product
struct Product: Codable {
let productName, productDescription, productIngredients: String?
let productPrice, volume: Int?
let image, interference, activeIngredients, howToUse: String?
let brandID, productTypeID: Int?
let brand, type: Brand?
let rating: JSONNull?
enum CodingKeys: String, CodingKey {
case productName = "product_name"
case productDescription = "product_description"
case productIngredients = "product_ingredients"
case productPrice = "product_price"
case volume, image, interference
case activeIngredients = "active_ingredients"
case howToUse = "how_to_use"
case brandID = "brand_id"
case productTypeID = "product_type_id"
case brand, type, rating
}
}
// MARK: - Brand
struct Brand: Codable {
let id: Int?
let name, createdAt, updatedAt, commission: String?
let category: Int?
enum CodingKeys: String, CodingKey {
case id, name
case createdAt = "created_at"
case updatedAt = "updated_at"
case commission, category
}
}
// MARK: - User
struct User: Codable {
let name, email: String?
let image1, deviceToken: JSONNull?
let account, followup: Bool?
enum CodingKeys: String, CodingKey {
case name, email, image1
case deviceToken = "device_token"
case account, followup
}
}
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
public var hashValue: Int {
return 0
}
public func hash(into hasher: inout Hasher) {
// No-op
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
Now this is the JSON model and how it's supposed to look:
{
"status": true,
"user_products": [
{
"id": 1,
"user_id": 1,
"product_id": 1,
"routine_time": "",
"created_at": "",
"updated_at": "",
"archived": 0,
"volume": 1,
"deleted_at": "",
"added_by": "",
"weekly_routine_one": "",
"weekly_routine_two": "",
"product": {
"product_name": "",
"product_description": "",
"product_ingredients": "",
"product_price": 1,
"volume": 1,
"image": "",
"interference": "",
"active_ingredients": "",
"how_to_use": "",
"brand_id": 1,
"product_type_id": 1,
"brand": {
"id": 1,
"name": "",
"created_at": "",
"updated_at": "",
"commission": ""
},
"type": {
"id": 1,
"name": "",
"created_at": "",
"updated_at": "",
"category": 1
},
"rating": null
},
"user": {
"name": "",
"email": "",
"image1": null,
"device_token": null,
"account": false,
"followup": false
},
"phase_out": 0,
"refill": 0,
"empty": 0,
"recommended": 0
}
]
}
You actually have two problems here.
1st, this is where your nils are coming from:
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
If you comment it out or make it do what you actually want it to do instead of what it's currently doing (making everything nil)... that'll bring us to problem #2
You'll have your data, but because it's all optionals, there's some unwrapping that needs to be done before it'll make much sense.

Decoding JSON Error: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil

I am trying to parse some JSON data with SwiftUI/Combine and I am a bit confused on the error I am getting. I am really new to Combine, so I could be completely overlooking something. I'm sure this has nothing to do with the real issue, as this would probably happen if I was parsing the normal way with urlsession/#escaping.
Here is the code:
struct FilmModel: Identifiable, Codable {
let adult: Bool
let backdropPath: String
let budget: Int
let genres: [Genre]
let homepage: String
let id: Int
let imdbID, originalLanguage, originalTitle, overview: String
let popularity: Double
let posterPath: String
let productionCompanies: [ProductionCompany]
let productionCountries: [ProductionCountry]
let releaseDate: String
let revenue, runtime: Int
let spokenLanguages: [SpokenLanguage]
let status, tagline, title: String
let video: Bool
let voteAverage: Double
let voteCount: Int
enum CodingKeys: String, CodingKey {
case adult
case backdropPath = "backdrop_path"
case budget
case genres
case homepage
case id
case imdbID = "imbd_id"
case originalLanguage = "original_language"
case originalTitle = "original_title"
case overview
case popularity
case posterPath = "poster_path"
case productionCompanies = "production_companies"
case productionCountries = "production_countries"
case releaseDate = "release_date"
case revenue
case runtime
case spokenLanguages = "spoken_languages"
case status, tagline, title
case video
case voteAverage = "vote_average"
case voteCount = "vote_count"
}
struct Genre: Identifiable, Codable {
let id: Int
let name: String
}
struct ProductionCompany: Codable {
let id: Int
let logoPath: String?
let name, originCountry: String
}
struct ProductionCountry: Codable {
let iso3166_1, name: String
}
struct SpokenLanguage: Codable {
let englishName, iso639_1, name: String
}
JSON response:
{
"adult": false,
"backdrop_path": "/rr7E0NoGKxvbkb89eR1GwfoYjpA.jpg",
"belongs_to_collection": null,
"budget": 63000000,
"genres": [
{
"id": 18,
"name": "Drama"
}
],
"homepage": "http://www.foxmovies.com/movies/fight-club",
"id": 550,
"imdb_id": "tt0137523",
"original_language": "en",
"original_title": "Fight Club",
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"popularity": 46.456,
"poster_path": "/pB8BM7pdSp6B6Ih7QZ4DrQ3PmJK.jpg",
"production_companies": [
{
"id": 508,
"logo_path": "/7PzJdsLGlR7oW4J0J5Xcd0pHGRg.png",
"name": "Regency Enterprises",
"origin_country": "US"
},
{
"id": 711,
"logo_path": "/tEiIH5QesdheJmDAqQwvtN60727.png",
"name": "Fox 2000 Pictures",
"origin_country": "US"
},
{
"id": 20555,
"logo_path": "/hD8yEGUBlHOcfHYbujp71vD8gZp.png",
"name": "Taurus Film",
"origin_country": "DE"
},
{
"id": 54051,
"logo_path": null,
"name": "Atman Entertainment",
"origin_country": ""
},
{
"id": 54052,
"logo_path": null,
"name": "Knickerbocker Films",
"origin_country": "US"
},
{
"id": 25,
"logo_path": "/qZCc1lty5FzX30aOCVRBLzaVmcp.png",
"name": "20th Century Fox",
"origin_country": "US"
},
{
"id": 4700,
"logo_path": "/A32wmjrs9Psf4zw0uaixF0GXfxq.png",
"name": "The Linson Company",
"origin_country": "US"
}
],
"production_countries": [
{
"iso_3166_1": "DE",
"name": "Germany"
},
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "1999-10-15",
"revenue": 100853753,
"runtime": 139,
"spoken_languages": [
{
"english_name": "English",
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "Mischief. Mayhem. Soap.",
"title": "Fight Club",
"video": false,
"vote_average": 8.4,
"vote_count": 22054
Data service:
class FilmDataService {
#Published var films: [FilmModel] = []
var filmSubscription: AnyCancellable?
init() {
getFilms()
}
private func getFilms() {
guard let url = URL(string: "https://api.themoviedb.org/3/movie/550?api_key=<key>") else { return }
filmSubscription = URLSession.shared.dataTaskPublisher(for: url)
.subscribe(on: DispatchQueue.global(qos: .default))
.tryMap { (output) -> Data in
guard let response = output.response as? HTTPURLResponse,
response.statusCode >= 200 && response.statusCode < 300 else {
throw URLError(.badServerResponse)
}
return output.data
}
.decode(type: [FilmModel].self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.sink { (completion) in
switch completion {
case .finished:
break
case .failure(let error):
print(error)
}
} receiveValue: { [weak self] (returnedFilms) in
self?.films = returnedFilms
self?.filmSubscription?.cancel()
}
}
View model:
class FilmViewModel: ObservableObject {
#Published var tabBarImageNames = ["house", "rectangle.stack", "clock.arrow.circlepath", "square.and.arrow.down"]
#Published var films: [FilmModel] = []
private let dataService = FilmDataService()
private var cancellables = Set<AnyCancellable>()
init() {
addSubscribers()
}
func addSubscribers() {
dataService.$films
.sink { [weak self] (returnedFilms) in
self?.films = returnedFilms
}
.store(in: &cancellables)
}
my observations. Your error is probably not to do with Combine.
you are trying to decode "[FilmModel].self", but the response is only for one film, FilmModel.self.
Also I would make most/all var in your FilmModel etc... optional, add "?".
It works well in my test.
EDIT:
This is the code I use to test my answer. Works well for me:
import Foundation
import SwiftUI
import Combine
#main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
#StateObject var movies = FilmViewModel()
var body: some View {
VStack (spacing: 50) {
Text("movie test")
ForEach(movies.films, id: \.id) { movie in
Text(movie.title ?? "no title").foregroundColor(.red)
}
}
}
}
class FilmDataService {
#Published var films: [FilmModel] = []
var filmSubscription: AnyCancellable?
init() {
getFilms()
}
private func getFilms() {
guard let url = URL(string: "https://api.themoviedb.org/3/movie/550?api_key=1f632307cea6ce33f288f9a232b9803b") else { return }
filmSubscription = URLSession.shared.dataTaskPublisher(for: url)
.subscribe(on: DispatchQueue.global(qos: .default))
.tryMap { (output) -> Data in
guard let response = output.response as? HTTPURLResponse,
response.statusCode >= 200 && response.statusCode < 300 else {
throw URLError(.badServerResponse)
}
return output.data
}
.decode(type: FilmModel.self, decoder: JSONDecoder()) // <--- here
.receive(on: DispatchQueue.main)
.sink { (completion) in
switch completion {
case .finished:
break
case .failure(let error):
print(error)
}
} receiveValue: { [weak self] (returnedFilms) in
self?.films.append(returnedFilms) // <--- here
self?.filmSubscription?.cancel()
}
}
}
class FilmViewModel: ObservableObject {
#Published var tabBarImageNames = ["house", "rectangle.stack", "clock.arrow.circlepath", "square.and.arrow.down"]
#Published var films: [FilmModel] = []
private let dataService = FilmDataService()
private var cancellables = Set<AnyCancellable>()
init() {
addSubscribers()
}
func addSubscribers() {
dataService.$films
.sink { [weak self] (returnedFilms) in
self?.films = returnedFilms
}
.store(in: &cancellables)
}
}
struct FilmModel: Identifiable, Codable {
let adult: Bool?
let backdropPath: String?
let budget: Int?
let genres: [Genre]?
let homepage: String?
let id: Int
let imdbID, originalLanguage, originalTitle, overview: String?
let popularity: Double?
let posterPath: String?
let productionCompanies: [ProductionCompany]?
let productionCountries: [ProductionCountry]?
let releaseDate: String?
let revenue, runtime: Int?
let spokenLanguages: [SpokenLanguage]?
let status, tagline, title: String?
let video: Bool?
let voteAverage: Double?
let voteCount: Int?
enum CodingKeys: String, CodingKey {
case adult
case backdropPath = "backdrop_path"
case budget
case genres
case homepage
case id
case imdbID = "imbd_id"
case originalLanguage = "original_language"
case originalTitle = "original_title"
case overview
case popularity
case posterPath = "poster_path"
case productionCompanies = "production_companies"
case productionCountries = "production_countries"
case releaseDate = "release_date"
case revenue
case runtime
case spokenLanguages = "spoken_languages"
case status, tagline, title
case video
case voteAverage = "vote_average"
case voteCount = "vote_count"
}
}
struct Genre: Identifiable, Codable {
let id: Int
let name: String?
}
struct ProductionCompany: Codable {
let id: Int
let logoPath: String?
let name, originCountry: String?
}
struct ProductionCountry: Codable {
let iso3166_1, name: String?
}
struct SpokenLanguage: Codable {
let englishName, iso639_1, name: String?
}
First of all, never write your api key (or any other keys) online!
Second of all:
It seems the endpoint that you are calling is returning a single FilmModel. So you have to decode it to a single one:
Change this:
.decode(type: [FilmModel].self, decoder: JSONDecoder())
to this:
.decode(type: FilmModel.self, decoder: JSONDecoder())
And then change this:
.sink { [weak self] (returnedFilms) in
self?.films = returnedFilms
}
to:
.sink { [weak self] (returnedFilm) in
self?.films = [returnedFilm]
}
Handle both single and multi object result
Some times you don't know if the server will return a single or multiple objects (and you don't have control on the server to fix that).
You can implement a custom decoder to handle both single and multi object responses:
enum FilmsResult {
case single(FilmModel)
case array([FilmModel])
}
extension FilmsResult: Decodable {
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let singleFilm = try? container.decode(FilmModel.self) {
self = .single(singleFilm)
} else {
try self = .array(container.decode([FilmModel].self))
}
}
}
extension FilmsResult {
var values: [FilmModel] {
switch self {
case .single(let film): return [film]
case .array(let films): return films
}
}
}
Than you can decode the result to:
.decode(type: FilmsResult.self, decoder: JSONDecoder())
and use it like:
.sink { [weak self] filmsResult in
self?.films = filmsResult.values
}

"Publishing changes from background threads is not allowed" while fetching data using URLSession

I am trying to fetch data from the Unsplash API however I am getting the following error: "Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates."
Here is the model struct:
// MARK: - UnsplashData
struct UnsplashData: Codable {
let id: String
let createdAt, updatedAt, promotedAt: Date
let width, height: Int
let color, blurHash: String
let unsplashDataDescription: String?
let altDescription: String
let urls: Urls
let links: UnsplashDataLinks
let categories: [String]
let likes: Int
let likedByUser: Bool
let currentUserCollections: [String]
let sponsorship: JSONNull?
let user: User
let exif: Exif
let location: Location
let views, downloads: Int
enum CodingKeys: String, CodingKey {
case id
case createdAt = "created_at"
case updatedAt = "updated_at"
case promotedAt = "promoted_at"
case width, height, color
case blurHash = "blur_hash"
case unsplashDataDescription = "description"
case altDescription = "alt_description"
case urls, links, categories, likes
case likedByUser = "liked_by_user"
case currentUserCollections = "current_user_collections"
case sponsorship, user, exif, location, views, downloads
}
}
// MARK: - Exif
struct Exif: Codable {
let make, model, exposureTime, aperture: String
let focalLength: String
let iso: Int
enum CodingKeys: String, CodingKey {
case make, model
case exposureTime = "exposure_time"
case aperture
case focalLength = "focal_length"
case iso
}
}
// MARK: - UnsplashDataLinks
struct UnsplashDataLinks: Codable {
let linksSelf, html, download, downloadLocation: String
enum CodingKeys: String, CodingKey {
case linksSelf = "self"
case html, download
case downloadLocation = "download_location"
}
}
// MARK: - Location
struct Location: Codable {
let title, name, city, country: String?
let position: Position
}
// MARK: - Position
struct Position: Codable {
let latitude, longitude: Double?
}
// MARK: - Urls
struct Urls: Codable {
let raw, full, regular, small: String
let thumb: String
}
// MARK: - User
struct User: Codable {
let id: String
let updatedAt: Date
let username, name, firstName, lastName: String
let twitterUsername: String?
let portfolioURL: String
let bio: String?
let location: String
let links: UserLinks
let profileImage: ProfileImage
let instagramUsername: String
let totalCollections, totalLikes, totalPhotos: Int
let acceptedTos: Bool
enum CodingKeys: String, CodingKey {
case id
case updatedAt = "updated_at"
case username, name
case firstName = "first_name"
case lastName = "last_name"
case twitterUsername = "twitter_username"
case portfolioURL = "portfolio_url"
case bio, location, links
case profileImage = "profile_image"
case instagramUsername = "instagram_username"
case totalCollections = "total_collections"
case totalLikes = "total_likes"
case totalPhotos = "total_photos"
case acceptedTos = "accepted_tos"
}
}
// MARK: - UserLinks
struct UserLinks: Codable {
let linksSelf, html, photos, likes: String
let portfolio, following, followers: String
enum CodingKeys: String, CodingKey {
case linksSelf = "self"
case html, photos, likes, portfolio, following, followers
}
}
// MARK: - ProfileImage
struct ProfileImage: Codable {
let small, medium, large: String
}
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
public var hashValue: Int {
return 0
}
public func hash(into hasher: inout Hasher) {
// No-op
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
And here is my ObservableObject:
class UnsplashAPI: ObservableObject {
enum State {
case loading
case loaded(UnsplashData)
}
#Published var state = State.loading
let url = URL(string: "https://api.unsplash.com/")!
func request() {
guard var components = URLComponents(url: url.appendingPathComponent("photos/random"),
resolvingAgainstBaseURL: true)
else {
fatalError("Couldn't append path component")
}
components.queryItems = [
URLQueryItem(name: "client_id", value: "vMDQ3Vzix8FN6MJL5Qpl3y0F7GdQsTtOjBe_L-IG2ro")
]
let request = URLRequest(url: components.url!)
let urlSession = URLSession(configuration: URLSessionConfiguration.default)
urlSession.dataTask(with: request) { data, urlResponse, error in
if let data = data {
let decoder = JSONDecoder()
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
decoder.dateDecodingStrategy = .formatted(dateFormatter)
do {
let response = try decoder.decode(UnsplashData.self, from: data)
self.state = .loaded(response) //error here
} catch {
print(error)
fatalError("Couldn't decode")
}
} else if let error = error {
print(error.localizedDescription)
} else {
fatalError("Didn't receive data")
}
}.resume()
}
}
Finally here is an example response I requested using Postman:
{
"id": "HWx5PYGudcI",
"created_at": "2020-12-08T22:11:11-05:00",
"updated_at": "2020-12-26T23:19:29-05:00",
"promoted_at": "2020-12-09T03:14:06-05:00",
"width": 4000,
"height": 6000,
"color": "#8ca6a6",
"blur_hash": "LAD,r_D*_M?^%ER4%$-oyYp0m+WE",
"description": null,
"alt_description": "boy in gray crew neck shirt",
"urls": {
"raw": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1",
"full": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=srgb&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=85",
"regular": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=1080",
"small": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=400",
"thumb": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=200"
},
"links": {
"self": "https://api.unsplash.com/photos/HWx5PYGudcI",
"html": "https://unsplash.com/photos/HWx5PYGudcI",
"download": "https://unsplash.com/photos/HWx5PYGudcI/download",
"download_location": "https://api.unsplash.com/photos/HWx5PYGudcI/download"
},
"categories": [],
"likes": 51,
"liked_by_user": false,
"current_user_collections": [],
"sponsorship": null,
"user": {
"id": "3Bj-zCFL4-g",
"updated_at": "2020-12-26T14:58:36-05:00",
"username": "owensito",
"name": "Owen Vangioni",
"first_name": "Owen",
"last_name": "Vangioni",
"twitter_username": null,
"portfolio_url": null,
"bio": "Capturing magical moments...\nInstagram: #owensitens 18 years",
"location": "Argentina ",
"links": {
"self": "https://api.unsplash.com/users/owensito",
"html": "https://unsplash.com/#owensito",
"photos": "https://api.unsplash.com/users/owensito/photos",
"likes": "https://api.unsplash.com/users/owensito/likes",
"portfolio": "https://api.unsplash.com/users/owensito/portfolio",
"following": "https://api.unsplash.com/users/owensito/following",
"followers": "https://api.unsplash.com/users/owensito/followers"
},
"profile_image": {
"small": "https://images.unsplash.com/profile-1583211530737-0c1a46227535image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32",
"medium": "https://images.unsplash.com/profile-1583211530737-0c1a46227535image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64",
"large": "https://images.unsplash.com/profile-1583211530737-0c1a46227535image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128"
},
"instagram_username": "owensitens",
"total_collections": 1,
"total_likes": 13,
"total_photos": 135,
"accepted_tos": true
},
"exif": {
"make": "NIKON CORPORATION",
"model": "NIKON D3300",
"exposure_time": "1/320",
"aperture": "5.3",
"focal_length": "45.0",
"iso": 200
},
"location": {
"title": null,
"name": null,
"city": null,
"country": null,
"position": {
"latitude": null,
"longitude": null
}
},
"views": 536045,
"downloads": 1267
}
You will need to switch thread to the main thread from which you are allowed (and only from it!) to make UI changes in iOS. To fix the error you will need to use GCD and simply wrap the line where you change your state in the async closure block.
DispatchQueue.main.async {
self.state = .loaded(response) // error should not be triggered anymore
}
add #MainActor before your class definition.

Swift parsing json read as nil

So i try to parse with jsondecoder and when i see in the log menu, all the data in json is nil. While the json i check in postman all have data on it
so here's the json i want to parse (*i just want to parse the row) :
{
" user": {
"command": "SELECT",
"rowCount": 1,
"oid": null,
"rows": [
{
"user_id": 193,
"u_name": "Gunawan Wibisono",
"email": "gunwibi89#gmail.com",
"div_name": "Design Aplication & Infrastructure",
"url": "2"
}
],
"fields": [
{
"name": "user_id",
"tableID": 1656774,
"columnID": 1,
"dataTypeID": 23,
"dataTypeSize": 4,
"dataTypeModifier": -1,
"format": "text"
},
{
"name": "u_name",
"tableID": 1656774,
"columnID": 2,
"dataTypeID": 1043,
"dataTypeSize": -1,
"dataTypeModifier": 54,
"format": "text"
},
{
"name": "email",
"tableID": 1656774,
"columnID": 3,
"dataTypeID": 1043,
"dataTypeSize": -1,
"dataTypeModifier": 259,
"format": "text"
},
{
"name": "div_name",
"tableID": 1656724,
"columnID": 2,
"dataTypeID": 1043,
"dataTypeSize": -1,
"dataTypeModifier": 259,
"format": "text"
},
{
"name": "url",
"tableID": 1656774,
"columnID": 9,
"dataTypeID": 1043,
"dataTypeSize": -1,
"dataTypeModifier": 259,
"format": "text"
}
],
"_parsers": [
null,
null,
null,
null,
null
],
"_types": {
"_types": {
"arrayParser": {}
},
"text": {},
"binary": {}
},
"RowCtor": null,
"rowAsArray": false
},
"status": 1
}
this is the code :
struct User : Codable {
let command : String?
let rowCount : Int?
let oid : Int?
let rows : [Rowss]?
}
struct Rowss : Codable {
let user_id: Int?
let u_name : String?
let email : String?
let div_name: String?
let url : String?
enum Codingkeys : String, CodingKey {
case user_id = "user_id"
case u_name = "u_name"
case email = "email"
case div_name = "div_name"
case url = "url"
}
}
func Json() {
let user = UserName.text
let pass = Password.text
let json = "http://ratings.immobispsa.com/getslogs/\(user!)/\(pass!)"
guard let myUrl = URL(string: json) else { return }
URLSession.shared.dataTask(with: myUrl) { (data, response, error) in
guard let data = data else {return}
do{
let user = try JSONDecoder().decode(User.self, from: data)
print("this is the json\(user)")
}catch{
print(error)
}
}.resume()
this is the log menu after i build :
"this is the jsonUser(command: nil, rowCount: nil, oid: nil, rows: nil)"
any idea where ive done wrong?
Your Codable structure is wrong. You should refer some tutorials for the same. Here is the Codable structure as per your response:
struct UserResponse: Codable {
let status: Int
let user: User
private enum CodingKeys: String, CodingKey {
case status
case user = " user"
}
}
struct User: Codable {
let command: String?
let rowCount: Int?
let oid: Int?
let rowCtor: Int?
let rowAsArray: Bool?
let rows: [Rows]?
let fields: [Fields]?
let parsers: [Parsers]?
let types: Type?
private enum CodingKeys: String, CodingKey {
case command
case rowCount
case oid
case rowCtor = "RowCtor"
case rowAsArray
case rows
case fields
case parsers = "_parsers"
case types = "_types"
}
}
struct Rows: Codable {
let userId: Int
let uName: String
let email: String
let divName: String
let url: String
private enum CodingKeys: String, CodingKey {
case userId = "user_id"
case uName = "u_name"
case email
case divName = "div_name"
case url
}
}
struct Fields: Codable {
let name: String
let tableID: Int
let columnID: Int
let datatypeID: Int?
let dataTypeSize: Int
let dataTypeModifier: Int
let format: String
private enum CodingKeys: String, CodingKey {
case name
case tableID
case columnID
case datatypeID
case dataTypeSize
case dataTypeModifier
case format
}
}
struct Parsers: Codable {
}
struct Types: Codable {
let types: Type?
let text: Text?
let binary: Binary?
private enum CodingKeys: String, CodingKey {
case types = "_types"
case text
case binary
}
}
struct Type: Codable {
}
struct Text: Codable {
}
struct Binary: Codable {
}
If any value can come as null, then only mark it as optional (?) otherwise don't, and in JSON your user key is having extra space at the front like " user", your API developer should fix it if possible.
Now decode it:
do{
let decodeResponse = try JSONDecoder().decode(UserResponse.self, from: data)
print("this is the json\(decodeResponse.user)")
}catch{
print(error)
}

How do I get this certain data set from json api in Swift?

I am currently using Tracker Networks Apex Legends API version 2.
I am trying to get the Legend’s data for each legend and then be able to show the data for each specific legend.
However, I cannot figure out an easy way of doing this.
Any ideas on how I could get something like...
Pathfinder
Kills - 100
Damage - 3000
Etc.
And do that for each legend.
JSON response:
{
"type": "legend",
"attributes": {
"id": "legend_8"
},
"metadata": {
"name": "Pathfinder",
"imageUrl": "https://trackercdn.com/cdn/apex.tracker.gg/legends/pathfinder-tile.png",
"tallImageUrl": "https://trackercdn.com/cdn/apex.tracker.gg/legends/pathfinder-tall.png",
"bgImageUrl": "https://trackercdn.com/cdn/apex.tracker.gg/legends/pathfinder-concept-bg-small.jpg",
"isActive": true
},
"expiryDate": "2019-10-04T21:59:04.1270197Z",
"stats": {
"kills": {
"rank": 208,
"percentile": 99.9,
"displayName": "Kills",
"displayCategory": "Combat",
"category": null,
"metadata": {},
"value": 12728,
"displayValue": "12,728",
"displayType": "Unspecified"
},
"killsAsKillLeader": {
"rank": 22,
"percentile": 99.9,
"displayName": "Kills As Kill Leader",
"displayCategory": "Combat",
"category": null,
"metadata": {},
"value": 5764,
"displayValue": "5,764",
"displayType": "Unspecified"
},
"sniperKills": {
"rank": 990,
"percentile": 99.7,
"displayName": "Sniper Kills",
"displayCategory": "Weapons",
"category": null,
"metadata": {},
"value": 104,
"displayValue": "104",
"displayType": "Unspecified"
},
"seasonWins": {
"rank": 31158,
"percentile": 92,
"displayName": "Season 1 Wins",
"displayCategory": "Game",
"category": null,
"metadata": {},
"value": 24,
"displayValue": "24",
"displayType": "Unspecified"
},
"seasonDamage": {
"rank": 5310,
"percentile": 98.8,
"displayName": "Season 1 Damage",
"displayCategory": "Game",
"category": null,
"metadata": {},
"value": 403954,
"displayValue": "403,954",
"displayType": "Unspecified"
}
}
},
"expiryDate": "2019-10-04T21:59:04.1270197Z"
}
You see I want to get this stats information for each legend and then display their name with whatever data on them is available inside a collection view or tableView. Probably collection view.
Structs used (done with QuickType):
struct Store: Codable {
let data: DataClass
enum CodingKeys: String, CodingKey {
case data = "data"
}
}
// MARK: - DataClass
struct DataClass: Codable {
let platformInfo: PlatformInfo
let userInfo: UserInfo
let metadata: DataMetadata
let segments: [Segment]
let availableSegments: [AvailableSegment]
//let expiryDate: ExpiryDate
enum CodingKeys: String, CodingKey {
case platformInfo = "platformInfo"
case userInfo = "userInfo"
case metadata = "metadata"
case segments = "segments"
case availableSegments = "availableSegments"
//case expiryDate = "expiryDate"
}
}
// MARK: - AvailableSegment
struct AvailableSegment: Codable {
let type: TypeEnum
let attributes: MetadataClass
enum CodingKeys: String, CodingKey {
case type = "type"
case attributes = "attributes"
}
}
// MARK: - MetadataClass
struct MetadataClass: Codable {
}
enum TypeEnum: String, Codable {
case legend = "legend"
case overview = "overview"
}
// MARK: - DataMetadata
struct DataMetadata: Codable {
let currentSeason: Int
let activeLegend: String
let activeLegendName: String
enum CodingKeys: String, CodingKey {
case currentSeason = "currentSeason"
case activeLegend = "activeLegend"
case activeLegendName = "activeLegendName"
}
}
// MARK: - PlatformInfo
struct PlatformInfo: Codable {
let platformSlug: String
let platformUserId: String
let platformUserHandle: String
let platformUserIdentifier: String
let avatarUrl: String
let additionalParameters: JSONNull?
enum CodingKeys: String, CodingKey {
case platformSlug = "platformSlug"
case platformUserId = "platformUserId"
case platformUserHandle = "platformUserHandle"
case platformUserIdentifier = "platformUserIdentifier"
case avatarUrl = "avatarUrl"
case additionalParameters = "additionalParameters"
}
}
// MARK: - Segment
struct Segment: Codable {
let type: TypeEnum
let attributes: SegmentAttributes
let metadata: SegmentMetadata
// let expiryDate: ExpiryDate
let stats: Stats
enum CodingKeys: String, CodingKey {
case type = "type"
case attributes = "attributes"
case metadata = "metadata"
//case expiryDate = "expiryDate"
case stats = "stats"
}
}
// MARK: - SegmentAttributes
struct SegmentAttributes: Codable {
let id: String?
enum CodingKeys: String, CodingKey {
case id = "id"
}
}
// MARK: - SegmentMetadata
struct SegmentMetadata: Codable {
let name: String
let imageUrl: String?
let tallImageUrl: String?
let bgImageUrl: String?
let isActive: Bool?
enum CodingKeys: String, CodingKey {
case name = "name"
case imageUrl = "imageUrl"
case tallImageUrl = "tallImageUrl"
case bgImageUrl = "bgImageUrl"
case isActive = "isActive"
}
}
// MARK: - Stats
struct Stats: Codable {
let level: ArKills?
let kills: ArKills
let damage: ArKills?
let headshots: ArKills?
let finishers: ArKills?
let arKills: ArKills?
let carePackageKills: ArKills?
let seasonWins: ArKills?
let seasonKills: ArKills?
let season2Wins: ArKills?
let rankScore: RankScore?
let smokeGrenadeEnemiesHit: ArKills?
let eyeEnemiesScanned: ArKills?
let grappleTravelDistance: ArKills?
enum CodingKeys: String, CodingKey {
case level = "level"
case kills = "kills"
case damage = "damage"
case headshots = "headshots"
case finishers = "finishers"
case arKills = "arKills"
case carePackageKills = "carePackageKills"
case seasonWins = "seasonWins"
case seasonKills = "seasonKills"
case season2Wins = "season2Wins"
case rankScore = "rankScore"
case smokeGrenadeEnemiesHit = "smokeGrenadeEnemiesHit"
case eyeEnemiesScanned = "eyeEnemiesScanned"
case grappleTravelDistance = "grappleTravelDistance"
}
}
// MARK: - ArKills
struct ArKills: Codable {
let rank: Int?
let percentile: Double?
let displayName: String
let displayCategory: DisplayCategory
let category: JSONNull?
let metadata: MetadataClass
let value: Double
let displayValue: String
let displayType: DisplayType
enum CodingKeys: String, CodingKey {
case rank = "rank"
case percentile = "percentile"
case displayName = "displayName"
case displayCategory = "displayCategory"
case category = "category"
case metadata = "metadata"
case value = "value"
case displayValue = "displayValue"
case displayType = "displayType"
}
}
enum DisplayCategory: String, Codable {
case combat = "Combat"
case game = "Game"
case weapons = "Weapons"
}
enum DisplayType: String, Codable {
case unspecified = "Unspecified"
}
// MARK: - RankScore
struct RankScore: Codable {
let rank: JSONNull?
let percentile: Int
let displayName: String
let displayCategory: DisplayCategory
let category: JSONNull?
let metadata: RankScoreMetadata
let value: Int
let displayValue: String
let displayType: DisplayType
enum CodingKeys: String, CodingKey {
case rank = "rank"
case percentile = "percentile"
case displayName = "displayName"
case displayCategory = "displayCategory"
case category = "category"
case metadata = "metadata"
case value = "value"
case displayValue = "displayValue"
case displayType = "displayType"
}
}
// MARK: - RankScoreMetadata
struct RankScoreMetadata: Codable {
let iconUrl: String
enum CodingKeys: String, CodingKey {
case iconUrl = "iconUrl"
}
}
// MARK: - UserInfo
struct UserInfo: Codable {
let isPremium: Bool
let isVerified: Bool
let isInfluencer: Bool
let countryCode: String
let customAvatarUrl: JSONNull?
let socialAccounts: JSONNull?
enum CodingKeys: String, CodingKey {
case isPremium = "isPremium"
case isVerified = "isVerified"
case isInfluencer = "isInfluencer"
case countryCode = "countryCode"
case customAvatarUrl = "customAvatarUrl"
case socialAccounts = "socialAccounts"
}
}
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
public var hashValue: Int {
return 0
}
public func hash(into hasher: inout Hasher) {
// No-op
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
Code used for api call and displaying data:
let PlayerStatURL = URL(string: "https://public-api.tracker.gg/v2/apex/standard/profile/origin/itsspress")
if let unwrappedURL = PlayerStatURL {
var request = URLRequest(url: unwrappedURL)
request.addValue("db833c37-1f45-4be4-a670-38272dba7504", forHTTPHeaderField: "TRN-Api-Key")
let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
// you should put in error handling code, too
if let data = data {
do {
let store = try JSONDecoder().decode(Store.self, from: data) as Store
print(store.data.platformInfo.avatarUrl)
print(store.data.platformInfo.platformUserHandle)
print("Level: \(store.data.segments[0].stats.level!.displayValue)")
print("lifetime Kills: \(store.data.segments.map{$0.stats.kills.displayValue}[0])")
print(store.data.segments.map{$0.metadata.name})
print(store.data.segments.map{$0.stats.carePackageKills?.displayName}[2])
} catch {
print(error.localizedDescription)
print(error)
}
}
}
dataTask.resume()
}
I am unsure how to get this data from the above JSON. The struct only seems to let me pull, let’s say kill stats, from all then legends and doesn’t let me just pull from let’s say pathfinder.
How could I just pull stats on pathfinder?
You can achieve that as below,
do {
let store = try JSONDecoder().decode(Store.self, from: data) as Store
store.data.segments.map{$0.metadata.name}.forEach { legendName in
if let stats = store.data.segments.first(where: { $0.metadata.name == legendName })?.stats {
let killString = stats.kills.displayName + " - " + stats.kills.displayValue
var damageString: String = ""
if let damage = stats.damage {
damageString = damage.displayName + " - " + damage.displayValue
}
print(legendName + " " + killString + " " + damageString )
}
}
} catch {
print(error.localizedDescription)
print(error)
}
Output:
Lifetime Kills - 408 Damage - 74,053
Pathfinder Kills - 230 Damage - 59,694
Gibraltar Kills - 1
Bangalore Kills - 116
Octane Kills - 0
Bloodhound Kills - 6
Wraith Kills - 18 Damage - 6,357
Mirage Kills - 14 Damage - 5,307
Caustic Kills - 7 Damage - 2,695
Lifeline Kills - 16