The main view on my app brings data from 3 different API calls.
So when the app starts, the data are still being returned, so nothing is seen but just a blank space.
They are basically a Thumbnail and its title.
What would be the best solution for that:
Have a temporary thumb and a text like "loading" OR
any other approach?
Thank you
Post
Replies
Boosts
Views
Activity
I have a button in MyViewA and after clicking on the button search, I want to call MyViewB, passing the variable search.
How can I call a different view after clicking a button ?
var search: String = "abc"
Button(action: {
MyViewB(keyword: self.search)
}) {
Text("Search")
}
Thank you
I have set in my info.plist file, the background and image I want for my launch screen.
The image is 200px x 200px and for some reason, when the launch screen happens, the image gets stretched, not keeping the original size.
How can I fix it ?
Thank you
When I run my app with my phone connected, suddenly the app crashes.
I don't have any information on the console, but I have the following message error in the @main line.
Thread 1: EXC_BAD_ACCESS (code=1, address=0x28)
@main
struct MyApp: App {
How can I know what is the problem and where to check for message errors when the app crashes ?
Thank you
I am trying to present a decimal variable containing the value of 66.67. So I am trying to do:
Text("\(myVariable, specifier: "%.2f")")
//Instance method 'appendinterpolation(_:specifier) requires that Decimal conform to _formtSpecifiable
Text("\(myVariable, specifier: "%.2f")" as String)
//I receive extra argument specifier in call
How can I fix it ?
Thx
struct MyView: View {
var body: some View {
//this value is coming from a JSON
var myDate = "3000-01-01T08:00:00-08:00"
//Here I'm calling my function formatDate, passing my myDate parameter:
Text(formatDate(dateString: myDate))
}
}
func formatDate(dateString: String) -> Date {
//first I dont know why my parameter gets here nil
let dateFormatter = ISO8601DateFormatter()
//at the dateFormatter, doesnt matter the options I set, the return is always the same.
dateFormatter.formatOptions = [
.withFullDate,
.withFullTime,
]
let finalDate = dateFormatter.date(from: dateString)!
return finalDate
}
I just need the get the date string, convert it to the format MM dd, yyyy - hh:mm
How can I do it ?
Thank you
I have an app where I am bringing some formatted text from the database.
The problem is when I use:
Text(myDataComingFromJson), of course, my text will be something like:
I've created an extension where I can remove the HTML tags but then all my text will be in only one paragraph and the lists won't exist ()
The second approach would use WKWebView but then I will have some headaches formatting text or loading extra views to do the job.
Question:
Is there a way to use Text directly, but keeping break lines and lists? Even though I have to change the content at the database level ?
I also have tried using \r\n in the database but still didn't work.
Is there a better solution?
Thank you all
I am trying to parse some html inside my app.
Not an entire html page, but just few blocks of html code.
So I'm using Ink package for that.
// FIRST I HAVE A WEBVIEW
import SwiftUI
import WebKitstruct WebView : UIViewRepresentable {
var html: String func makeUIView(context: Context) -> WKWebView {
return WKWebView()
} func updateUIView(_ webView: WKWebView, context: Context) {
webView.loadHTMLString(html, baseURL: nil)
}}
// IN HERE I'M PARSING THE HTML AND ALSO ADDING SOME STYLING TO IT
import Foundation
import Ink
class ParseContent: ObservableObject {
var markdown: String = ""
func parse() -> String {
let parser = MarkdownParser()
let html = parser.html(from: markdown)
let htmlStart = "<HTML><HEAD></HEAD><BODY style=\"padding: 140px; font-size: 120px; font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Open Sans,Helvetica Neue,sans-serif\">"
let htmlEnd = "</BODY></HTML>"
return htmlStart + html + htmlEnd
}
}
// IN HERE I AM JUST USING MY PREVIOUSLY CREATED WEBVIEW
WebView(html: myHtmlContent)
.onAppear() {
htmlContent = ParseContent().parse()
}
So here are my questions:
Why the styling isn't working since I am concatenating the html ? I see it in a lot of tutorials but cant understand why not working.
I would like to have the font inside my WebView, the same as I have for my other components like Text("abc") so I would keep a pattern and the visitor woudnt realize they are different components.
How to set the WebView without a vertical scroll ? Keeping the entire height coming from the parsed html ?
Thank you guys :)
I have an ObservableObject class that can return 2 different @published vars (product or products), depending on the function I call.
But when I define the published vars, I am having an error message "Missing argument for parameter 'from' in call".
It just happens for the first published var.
What's the mistake?
Thx
class ProductStore: ObservableObject {
@Published var product = ProductModel() //getting error here
@Published var products: [ProductModel] = []
func getProducts() {
ProductApi().getProducts() { (products) in
self.products.append(contentsOf: products)
}
}
func getProductById(productId: Int) {
ProductApi().getProductById(productId: productId) { (product) in
self.product = product
} }
}
I have a JSON from my backend which returns:
[
{
productId : 1
name: productA
},
{
productid: 2
name: productB
}
}
And on my SwiftUI project I have a model:
struct ProductModel: Identifiable, Codable, Hashable {
//var id = UUID()
var productId = Int
var name = String
}
In my View, when I do a foreach to present all the products coming from my JSON, I got a message saying my model needs to be Identifiable to be using the foreach.
That was the reason I created the var id = UUID() on my model.
Now I dont have the foreach error message, however, I get the error:
Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "id", intValue: nil)
Shouldn't it be ok since I am creating the ID on my model ?
Thank you !
Trying to understand API calls in SwiftUI, I got some doubt about environmentObject.Here, I have a file Network.swift which contains a method to get Users.
So I create an environmentObject on my ProjectNameApp.swift file (see code).But this is my question:
Let's say I have an another file Products.swift containing methods related to the products API. How I would set it in my ProjectNameApp.swift file ?
// Network.swift
import SwiftUIclass Network: ObservableObject {
@Published var users: [User] = [] func getUsers() {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { fatalError("Missing URL") } let urlRequest = URLRequest(url: url) let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if let error = error {
print("Request error: ", error)
return
} guard let response = response as? HTTPURLResponse else { return } if response.statusCode == 200 {
guard let data = data else { return }
DispatchQueue.main.async {
do {
let decodedUsers = try JSONDecoder().decode([User].self, from: data)
self.users = decodedUsers
} catch let error {
print("Error decoding: ", error)
}
}
}
} dataTask.resume()
}
}
// ProjectNameApp.swift@main
struct ProjectNameApp: App {
var network = Network() var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(network)
}
}
}
Would be the right implementation something like this ? For each API group a new environmentObject ?
// ProjectNameApp.swift@main
struct ProjectNameApp: App {
var network = Network()
var product = Product() var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(network)
.environmentObject(product)
}
}
}
Thank you
Checking an existing code, I could see an environmentObject set in my main file.
What does it mean ? it means I am creating an instance of my store and making them available for the entire application ? Like a static instance in other languages ? or there is something else ?
Thank you,
@main
struct myApp: App {
var myStore = MyStore()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(myStore)
When developing my code, I have seen people saying I should create a Store (eg: ProductStore) with ObservableObject/Published and inside of it, create functions to call the API (eg: ProductAPI)
What's the reason for that ?
Thank you
I have this API call in my application.
For some reason, the response is coming back nil.
If I try the right URL, a JSON will be returned and all the nodes filled out.
So I'm trying to get the error inside the
if let error = error { but even putting a breaking point in there, the code is never reached.
What am I doing wrong ?
Thanks
func getProductById(productId: Int, completion: @escaping (ProductModel) -> ()) {
guard let url = URL(string: "https://mysite/api/products/82") else { return } var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: request) { (data, request, error) in
if let data = data {
print("data") } if let error = error {
print("error") }
guard let data = data else { return } do {
let product = try! JSONDecoder().decode(ProductModel.self, from: data)
DispatchQueue.main.async {
completion(product)
}
} catch {
print(error)
} }
.resume()
When instanciating an array of ProductModel, I do this way and everything works fine:
@Published var products = [ProductModel]()
However If I just want one instance, I have an error:
@Published var product = ProductModel()
Missing argument for parameter 'from' in call
Why is this problem happening ?
Thx