I am trying to build an application which receives a JSON Object from an API endpoint, which then I want to list out in the view. I've watched a lot of videos on this topic, but in each video they use very simplistic JSON Objects as examples and therefore the code they write doesn't really seem to transfer over, giving me errors no matter how I try to format it. The code is as follows
import SwiftUI
import Combine
import Foundation
public struct ActivityModel: Codable, Identifiable {
public let id: Int
public let name: String
public let activity_desc: String?
}
public struct ActivitiesModel2: Codable {
public let location: String
public let popular: [String:ActivityModel]
}
public struct ActivitiesModel: Codable {
public let activities: ActivitiesModel2
}
public class ActivityFetcher: ObservableObject {
var activities: ActivitiesModel?
init(){
guard let url = URL(string: "https://mywebsite.com/api/loadapi") else { return }
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
do {
if let d = data {
let decodedLists = try JSONDecoder().decode(ActivitiesModel.self, from: d)
DispatchQueue.main.async {
self.activities = decodedLists
}
} else {
print("No Data")
}
} catch {
print("Error")
}
}.resume()
}
}
struct ActivityGuestView: View {
let networkingServiceGeneral = NetworkingServiceGeneral()
#ObservedObject var viewRouter: ViewRouter
#ObservedObject var fetcher = ActivityFetcher()
var body: some View {
// This is where my issues start
List(fetcher.activities?.activities.popular) { result in
VStack {
Text(result.name)
Text(result.activity_desc)
.font(.system(size: 11))
.foregroundColor(Color.gray)
}
}
}
}
This code, as I put it, gives me 5 errors. They are the following;
- Initializer 'init(_:rowContent:)' requires that '(key: String, value: ActivityModel)' conform to Identifiable
- Initializer 'init(_:rowContent:)' requires that '[String : ActivityModel]' conform to 'RandomAccessCollection'
-Value of optional type '[String : ActivityModel]?' must be unwrapped to a value of type '[String : ActivityModel]'
- Coalesce using '??' to provide a default when the optional value contains 'nil'
- Force-unwrap using '!' to abort execution if the optional value contains 'nil'
Some of these errors have options to fix it, but when I press fix it adds code but doesn't actually fix the error so I figured to just include them anyways. I'm still fairly new to Swift, but I know what some of it is asking, particularly the conforming to Identifiable, but it says that struct ActivitiesModel does not conform to identifiable when I try to add the tag, and the JSON Object doesn't have an ID for that section, so I can't ask the ID to make it identifiable.
Any help would be greatly appreciated, this has kind of been a wall right now.
Here's the JSON
"activities": {
"location": "Dallas",
"popular": {
"10": {
"id": 38,
"name": "Adventure Landing Dallas",
"activity_desc": "Aquatic complex chain with additional land attractions including mini-golf, laser tag & go-karts.",
},
"12": {
"id": 40,
"name": "Jumpstreet",
"activity_desc": "None provided.",
},
}
}
}
You have a couple of issues here.
First, dictionaries and Lists aren't compatible; You really need an array. As the errors say, the item that is supplied to a List needs to confirm to Identifiable and RandomAccessCollection. A dictionary conforms to neither and you can't really make it do so.
Your second issue is that fetcher.activities is an optional and the List initialiser can't accept an optional. The compiler is suggesting a couple of alternatives - Supply a default value using the nil coalescing operator (??) or force unwrap using ! (Which will crash, since you know that fetcher.activities is going to be nil initially.
The root cause of the first problem is that your JSON has variable keys rather than a simple array of activities. This is not a great idea and you should really put some work in on the server side to eliminate the meaningless numeric key and have a simple array, as per my comment, however you have indicated that you can't do this.
Given this, another approach is to expose the dictionary values as an array using a computed property:
public struct ActivitiesModel2: Codable {
public let location: String
private var popular: [String:ActivityModel]
public var popularActivities: [ActivityModel] {
get {
return Array(self.popular.values)
}
}
}
While we are here, we can fix that un-Swifty activity_desc with a CodingKeys enumeration:
public struct ActivityModel: Codable, Identifiable {
public let id: Int
public let name: String
public let activityDesc: String?
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
case activityDesc = "activity_desc"
}
}
Now, you can re-write your view to use the new computed property and to handle the optional:
struct ActivityGuestView: View {
let networkingServiceGeneral = NetworkingServiceGeneral()
#ObservedObject var viewRouter: ViewRouter
#ObservedObject var fetcher = ActivityFetcher()
var body: some View {
// This is where my issues start
List(fetcher.activities?.activities.popularActivities ?? []) { result in
VStack {
Text(result.name)
Text(result.activity_desc)
.font(.system(size: 11))
.foregroundColor(Color.gray)
}
}
}
}
Related
This is on iOS 15.5 using the latest SwiftUI standards.
I have these two structs in my SwiftUI application:
User.swift
struct User: Codable, Identifiable, Hashable {
let id: String
let name: String
var socialID: String? // it's a var so I can modify it later
func getSocialID() async -> String {
// calls another API to get the socialID using the user's id
// code omitted
// example response:
// {
// id: "aaaa",
// name: "User1",
// social_id: "user_1_social_id",
// }
}
}
Video.swift
struct Video: Codable, Identifiable, Hashable {
let id: String
let title: String
var uploadUser: User
}
My SwiftUI application displays a list of videos, the list of videos are obtained from an API (which I have no control over), the response looks like this:
[
{
id: "AAAA",
title: "My first video. ",
uploaded_user: { id: "aaaa", name: "User1" },
},
{
id: "BBBB",
title: "My second video. ",
uploaded_user: { id: "aaaa", name: "User1" },
},
]
My video's view model looks like this:
VideoViewModel.swift
#MainActor
class VideoViewModel: ObservableObject {
#Published var videoList: [Video]
func getVideos() async {
// code simplified
let (data, _) = try await URLSession.shared.data(for: videoApiRequest)
let decoder = getVideoJSONDecoder()
let responseResult: [Video] = try decoder.decode([Video].self, from: data)
self.videoList = responseResult
}
func getSocialIDForAll() async throws -> [String: String?] {
var socialList: [String: String?] = [:]
try await withThrowingTaskGroup(of: (String, String?).self) { group in
for video in self.videoList {
group.addTask {
return (video.id, try await video.uploadedUser.getSocialId())
}
}
for try await (userId, socialId) in group {
socialList[userId] = socialId
}
}
return socialList
}
}
Now, I wish to fill in the socialID field for the User struct, which I must obtain from another API using each user's ID. the response looks like this for each user:
{
id: "aaaa",
name: "User1",
social_id: "user_1_social_id",
}
Right now the only viable way to get the information seems to be using withThrowingTaskGroup() and call getSocialID() for each user, which I am using right now, then I can return a dictionary that contains all the socialID information for each user, then the dictionary can be used in SwiftUI views.
But, is there a way for me to fill in the socialID field in the User struct without having to use a separate dictionary? It doesn't seem like I can modify the User struct in each Video inside videoList once the JSON decoder initializes the list of videos, due to the fact that VideoViewModel is a MainActor. I would prefer to have everything downloaded in one go, so that when the user enters a subview, there is no loading time.
You are correct that you can't modify the structs once they are initialized, because all of their properties are let variables; however, you can modify the videoList in VideoViewModel, allowing you to dispense with the Dictionary.
#MainActor
class VideoViewModel: ObservableObject {
#Published var videoList: [Video]
func getVideos() async {
// code simplified
let (data, _) = try await URLSession.shared.data(for: videoApiRequest)
let decoder = getVideoJSONDecoder()
let responseResult: [Video] = try decoder.decode([Video].self, from: data)
self.videoList = try await Self.getSocialIDForAll(in: responseResult)
}
private static func updatedWithSocialID(_ user: User) async throws -> User {
return User(id: user.id, name: user.name, socialID: try await user.getSocialID())
}
private static func updatedWithSocialID(_ video: Video) async throws -> Video {
return Video(id: video.id, title: video.title, uploadUser: try await updatedWithSocialID(video.uploadUser))
}
static func getSocialIDForAll(in videoList: [Video]) async throws -> [Video] {
return try await withThrowingTaskGroup(of: Video.self) { group in
videoList.forEach { video in
group.addTask {
return try await self.updatedWithSocialID(video)
}
}
var newVideos: [Video] = []
newVideos.reserveCapacity(videoList.count)
for try await video in group {
newVideos.append(video)
}
return newVideos
}
}
}
Using a view model object is not standard for SwiftUI, it's more of a UIKit design pattern but actually using built-in child view controllers was better. SwiftUI is designed around using value types to prevent the consistency errors typical for objects so if you use objects then you will still get those problems. The View struct is designed to be the primary encapsulation mechanism so you'll have more success using the View struct and its property wrappers.
So to solve your use case, you can use the #State property wrapper, which gives the View struct (which has value semantics) reference type semantics like an object would, use this to hold the data that has a lifetime matching the View on screen. For the download, you can use async/await via the task(id:) modifier. This will run the task when the view appears and cancel and restart it when the id param changes. Using these 2 features together you can do:
#State var socialID
.task(id: videoID) { newVideoID in
socialID = await Social.getSocialID(videoID: newViewID)
}
The parent View should have a task that got the video infos.
I have a data class that shows:
import SwiftUI
struct ApiMovieStruct: Hashable, Codable, Identifiable {
var poster_path: String
var overview: String
var release_date: String
var id: String
var title: String
}
and I keep getting these errors from this view
struct SearchApiList: View {
var body: some View {
List {
ForEach(foundMoviesList) { aMovie in
NavigationLink(destination: SearchApiDetails(movie: aMovie)) {
SearchApiItems(movie: aMovie)
}
}
}
.navigationBarTitle(Text("Search Results"), displayMode: .inline)
}
}
struct SearchApiList_Previews: PreviewProvider {
static var previews: some View {
SearchApiList()
}
}
On the line ForEach(foundMoviesList) there is an error I get where: Generic Parameter 'C' could not be inferred, Cannot convert value of type '[ApiMovieStruct]' to expected argument type 'Binding'
Do you guys know why this is happening?
foundMoviesList can be found below, there is more code, but I think this might be enough. Thank you all.
import Foundation
import SwiftUI
// Global array of API Recipe structs
var foundMoviesList = [ApiMovieStruct]()
fileprivate var previousQuery = ""
public func obtainDataFromApi(apiQueryUrl: String) {
// Avoid executing this function if already done for the same query URL
if apiQueryUrl == previousQuery {
return
} else {
previousQuery = apiQueryUrl
}
// Clear out previous content in the global array
foundMoviesList = [ApiMovieStruct]()
```
Say I have some enum, Channel, filled with sample property data:
enum Channel: CaseIterable {
case abc
case efg
case hij
var name: String {
switch self {
case .abc: return "ABC"
case .efg: return "EFG"
case .hij: return "HIJ"
}
}
}
extension Channel: Identifiable {
var id: Self { self }
}
And some view implementation to fill said content with:
struct ChannelHome: View {
var body: some View {
VStack {
ForEach(Channel.allCases) { channel in
NavigationLink(destination: ChannelDetail(channel)) {
Text(channel.name)
}
}
}
}
} // big closure yikes
Why doesn't this work? Is this due to the nature of enums not having static properties and SwiftUI being declarative? Are there ways around this? Such as:
struct ChannelData {
static let channels: [Channel] = [.abc, .efg, .hij]
// or
static func getChannels() -> [Channel] {
var channelArray: [Channel]
for channel in Channel.allCases {
channelArray.append(channel)
}
return channelArray
}
}
Or, more preferably, are there better practices for presenting small data sets like these in a SwiftUI view? I like being able to implement a visual UI of my properties for when I'm debugging, as a whole, at runtime (closer to the production stage).
I apologies in advance for the question, I am just getting into it with SwiftUI.
Here are 2 simple ways for you, but not sure where can be helpful for you because with enum you cannot update ForEach elements, but it has a use case for showing data!
First way without any Identifiable id:
struct ContentView: View {
var body: some View {
ForEach(TestEnum.allCases, id: \.rawValue) { item in
Text(item.rawValue)
}
}
}
enum TestEnum: String, CaseIterable { case a, b, c }
with Identifiable id that conforms to Identifiable protocol, you can cut , id: \.id even:
struct ContentView: View {
var body: some View {
ForEach(TestEnum.allCases, id: \.id) { item in
Text(item.rawValue)
}
}
}
enum TestEnum: String, CaseIterable, Identifiable { case a, b, c
var id: String { return self.rawValue }
}
Either Xcode was getting hung up on cache errors or I am a fool (probably the latter). Regardless, the issue seems to have been resolved with the following Identifiable extension to your enum, as well as a good ol' derived data purge and clean:
extension Channel: Identifiable {
var id: Self { self }
}
I seem to have confused this issue with another long-time issue that I've constantly run into; mostly regarding enums and their distaste for storing static data (as is simply just the nature of their fast and lite structure).
NOTE: Forgive my cluelessness, i am still new in regards to this. The full code is posted at the bottom.
ISSUE: It seems that when i have a short nest, i am able to call it for my #Published property however when i try an api request with a longer nest, like this. and type Decodable structs that follows the structure of the GET request
struct TripScheduleTest: Codable {
let TripList: InitialNest
}
struct InitialNest: Codable {
var Trip: [TravelDetail]
}
struct TravelDetail: Codable {
var Leg: [TripTest]
}
struct TripTest: Codable, Hashable {
var name: String
var type: String
}
I am not able to call it for the #Published var dataSet1 = [TripTest]()
self.dataSet1 = tripJSON.TripList.Trip.Leg
I get an error message, that says "Value of type '[TravelDetail]' has no member 'Leg'
I am not sure why, however it works when i use [TravelDetail]() instead of [TripTest]() in the #Published var and stop at Trip before Leg for the dataSet1, then it seems to at least build successfully. But now i am not able to get the name and type information from the request
Full code
import SwiftUI
struct TripScheduleTest: Codable {
let TripList: InitialNest
}
struct InitialNest: Codable {
var Trip: [TravelDetail]
}
struct TravelDetail: Codable {
var Leg: [TripTest]
}
struct TripTest: Codable, Hashable {
var name: String
var type: String
}
class TripViewModel: ObservableObject {
#Published var dataSet1 = [TripTest]()
init() {
let urlString = "http://xmlopen.rejseplanen.dk/bin/rest.exe/trip?originId=8600790&destId=6553&format=json"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, resp, err) in
guard let data = data else { return }
do {
let tripJSON = try
JSONDecoder().decode(TripScheduleTest.self, from: data)
print(data)
DispatchQueue.main.async {
self.dataSet1 = tripJSON.TripList.Trip.Leg
}
} catch {
print("JSON Decode error: ", error)
}
}.resume()
}
}
struct TripView: View {
#ObservedObject var vm = TripViewModel()
var body: some View {
List(vm.dataSet1, id: \.self) { day in
Text("Test")
.font(.system(size: 12, weight: .bold))
Text(" \(day.name)")
.font(.system(size: 12))
}
}
}
Trip is an array (note the [])
You need to get one item of the array by index for example
tripJSON.TripList.Trip.first?.Leg
To assign the value to a non-optional array write
self.dataSet1 = tripJSON.TripList.Trip.first?.Leg ?? []
I have a simple view below to display all of the contacts for the user:
struct AllContactsView: View {
static let withState: some View = AllContactsView().environmentObject(AllContactsProvider())
#EnvironmentObject var contactsProvider: AllContactsProvider
let title: UserListType = .selectInvitees
var body: some View {
List(self.contactsProvider.invitees) { invite in
self.row(for: invite)
}
.navigationBarTitle(Text(self.title.rawValue))
.onAppear(perform: self.contactsProvider.fetch)
}
func row(for invite: Invitee) -> some View {
// everything below is only printed out once!
print(self.contactsProvider.invitees.prettyPrinted) // shows correct array of contacts
print(type(of: self.contactsProvider.invitees)) // this is indeed an array
print(invite) // prints out the first item in the array (which is expected on first pass)
return UserRow(invitee: invite)
}
}
I am manipulating the array of CNContacts I get like this to an array of Invitees, which is what I am attempting to display in my list:
self?.invitees = contacts.asSimpleContacts.map({ $0.asUser.asInvitee })
Using the supporting functions and extensions below:
// Contact Value simplified so we can pass it around as a value type.
public struct SimpleContact: Hashable, Codable {
let firstName: String
let lastName: String
let emails: [String]
let phoneNumbers: [PhoneNumber]
var fullName: String { "\(self.firstName) \(self.lastName)" }
var asUser: User {
User(
id: Constants.unsavedID,
username: self.fullName,
picURL: "al",
email: self.emails.first ?? "",
phone: self.phoneNumbers.first ?? "",
created: Date().timeIntervalSince1970
)
}
}
extension CNContact {
/// Returns the `SimpleContact` representation of `self`
var asSimpleContact: SimpleContact {
SimpleContact(
firstName: self.givenName,
lastName: self.familyName,
emails: self.emailAddresses.map({ String($0.value) }),
phoneNumbers: self.phoneNumbers.map({ Authentication.sanitize(phoneNo: $0.value.stringValue) })
)
}
}
extension Array where Element == CNContact {
/// Returns the `SimpleContact` mapping of `self`
var asSimpleContacts: [SimpleContact] { self.map({ $0.asSimpleContact }) }
}
public struct User: Hashable, Codable, Identifiable {
public let id: String
let username: String
let picURL: String
let email: String
let phone: String
let created: Double
var asInvitee: Invitee { Invitee(user: self, isGoing: false) }
}
The contacts are populated into self.contactsProvider.invitees as expected following self.contactsProvider.fetch(). However, SwiftUI is displaying self.contactsProvider.invitees.count instances of self.contactsProvider.invitees.first, rather than each contact. I have compared my approach below to other examples online and can't seem to find where I went wrong. I have determined that the issue lies somewhere with the contacts manipulation - when I supply a mocked array of invitees, everything works as expected, despite things compiling and running as expected without the mocks, and printing and debugging not revealing anything.
Any help would be appreciated.
I just ran into this issue, to answer a bit more clearly:
Each row in a SwiftUI list should be generated with a unique ID.
If you are using the List() function to create the view, make sure you are specifying an id
struct MenuView: View {
var body: some View {
VStack {
Section(header: MenuSectionHeader()) {
//item.sku is the unique identifier for the row
List(Menu.allItems, id:\.sku) { item in
MenuItemRow(item)
}
}
}
}
For anyone who runs across something similar, the problem was that the ID I was instantiating the objects with was not unique. Curious that this would be the expected behavior if that error is made, but thats what it was.