Hi there! I'm new with iOS development so I know that my question is quite easy for you guys. It would be great is you could help me to keep moving forward. I'm trying to request data from an API when a view appears. Here is my code:
import SwiftUI
// Define data structure for API function
struct DescriptionResponse: Codable {
var results: [DescriptionResult]
}
struct DescriptionResult: Codable {
var id: String
var symbol: String
var cik: Int
var name: String
var sic: Int
var sector: String
var location: String
var mailing_address: String
var business_address: String
var business_latitude: Float
var business_longitude: Float
}
struct DescriptionScreen: View {
var selectedCik: Int
@State var descriptionResults = [DescriptionResult]() // define State variable for API Function
var body: some View {
ZStack {
Color("CustomBackground")
.edgesIgnoringSafeArea(.all)
VStack {
Maps(Lat: 34, Long: -116, LatSpan: 2, LongSpan: 2).cornerRadius(20)
.edgesIgnoringSafeArea(.all)
HStack {
RoundedRectangle(cornerRadius: 20)
.shadow(color: Color.gray.opacity(0.2), radius: 5)
.foregroundColor(.white)
.padding()
.overlay(Text("SYMBOL")
.font(.title)
.fontWeight(.semibold))
RoundedRectangle(cornerRadius: 20) // Spacer() is not working
.foregroundColor(Color("CustomBackground"))
}
.frame(height: 100.0)
RoundedRectangle(cornerRadius: 20)
.padding()
.foregroundColor(.white)
.shadow(color: Color.gray.opacity(0.2), radius: 5)
.overlay(
Text("DESCRIPTION")
.multilineTextAlignment(.leading)
.padding(.all, 30.0)
, alignment: .top
)
}
}.onAppear {
self.descriptionRequest(url: "myURL")
}
}
// Define function API Request
func descriptionRequest(url: String) {
// First replace spaces for & in the parameter (searchText)
let urlEncode = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? url
guard let url = URL(string: urlEncode) else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, reponse, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(DescriptionResponse.self, from: data) {
DispatchQueue.main.async {
self.descriptionResults = decodedResponse.results
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
}
The problem is when I do in the body Text(descriptionResults[0].symbol)
I get an error because the array is empty. If I put a print
statement before the return
of the function, It prints the array correctly. What am I missing?
Thank you
Dennis
Post
Replies
Boosts
Views
Activity
Hi guys!
Sincerely I don't know what title should I put to this post. Anyway, hope you can help me :)
I have a function that request some data to my webserver. Everything works fine when the function is in the same structure as the body, but when I write this function in a different file, and then call it to my Struct (body file), the @State that should return is not returning it anymore ( it is empty).
Here is my code:
Function file
import SwiftUI
struct DescriptionFunction {
		
		// Result variable
		@State var companyDescriptionResult = [CompanyDescriptionResult]()
		
		// Define function API Request
		func descriptionRequest(url: String) {
				
				
				// First replace spaces for & in the parameter (searchText)
				let urlEncode = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? url
				
				guard let url = URL(string: urlEncode) else {
						print("Invalid URL")
						return
				}
				let request = URLRequest(url: url)
				
				URLSession.shared.dataTask(with: request) { data, reponse, error in
						if let data = data {
								if let decodedResponse = try? JSONDecoder().decode(CompanyDescriptionResponse.self, from: data) {
										DispatchQueue.main.async {
												
												self.companyDescriptionResult = decodedResponse.results
												
										}
										
										return
								}
						}
						print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
						
				}.resume()
				
		}
}
View
struct CompanyDescriptionScreen: View {
		
		var descriptionFunction = DescriptionFunction()
		
		var body: some View {
				VStack {
						Text("1")
								.onAppear {
										descriptionFunction.descriptionRequest(url: "myURL")
										
								}
						
						Button(action: {print(descriptionFunction.companyDescriptionResult)}) {
								Text("print")
						}
				}
				
		}
}
When I click this button, it prints an empty array, when it shouldn't. If I write the function directly in the same view file and structure, it returns the actual value.
Thank you.
Dennis
Hi guys! Today I'm quite confused about how to approach this problem that I'm going to explain you. It would be great if you could help me.
First, I just accomplished successfully the Apple tutorial to create a dynamic list from a local JSON file. But know, I need it from a JSON web server response. I'm receiving the data correctly into my app (I can print it and use it) but I don't know how to create a dynamic list with it. Let's write some code.
Example data (Response)
{"results":[{"tag":"AccountsPayableCurrent","valueNum":266099000,"valueId":"USD","endtime":"20131231"},
{"tag":"AccountsPayableRelatedPartiesCurrent","valueNum":38000,"valueId":"USD","endtime":"20131231"},
{"tag":"AccountsReceivableNetCurrent","valueNum":243930000,"valueId":"USD","endtime":"20131231"},
{"tag":"AccruedLiabilitiesCurrent","valueNum":5583000,"valueId":"USD","endtime":"20131231"},
{"tag":"AccumulatedDepreciationDepletionAndAmortizationPropertyPlantAndEquipment","valueNum":120568000,"valueId":"USD","endtime":"20131231"}]}
Data Model
import SwiftUI
struct CompanyFinancialReportResponse: Codable {
var results: [CompanyFinancialReportResult]
}
struct CompanyFinancialReportResult: Codable {
var tag: String
var valueNum: Float
var valueId: String
var endtime: String
}
Function request
import SwiftUI
class CompanyFinancialReportFuction: ObservableObject {
// Result variable. I have to make it with @Published
@Published var companyFinancialReportResult = [CompanyFinancialReportResult]()
@Published var financialReportShowResult: Bool = false
// Define function API Request
func financialReportRequest(url: String) {
// First replace spaces for & in the parameter (searchText)
let urlEncode = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? url
guard let url = URL(string: urlEncode) else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, reponse, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(CompanyFinancialReportResponse.self, from: data) {
DispatchQueue.main.async {
func getValues () -> Bool {
self.companyFinancialReportResult = decodedResponse.results
return true
}
if getValues() {
self.financialReportShowResult = true
}
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
}
As usual, then I'm calling the function from another structure .onAppear
and receiving the data.
As I said, everything is working, the thing is I don't know how to create a list. I would like to make it in the following way:
1) Create a structure called FinancialRow -> design the row
2) Create a list in the main view
Thank you
Dennis
Hi guys! I'm trying to implement a DatePicker in my app, everything works find except for one thing. When I select the DatePicker I receive this huge warning (I attached a text file that contains the full warning).
[LayoutConstraints] Unable to simultaneously satisfy constraints.
This is only the first part of the warning. Please check the full error attached.
Full error - https://developer.apple.com/forums/content/attachment/6491a943-116e-4154-aca7-076ce4742ec9
On an iPhone, the DatePicker looks good but on an iPad it is very small relative to the iPad screen.
This is my code
// Date picker
DatePicker(selection: $selectedDate, in: ...Date(), displayedComponents: .date) {
Text("")
}
.padding(.trailing)
.onChange(of: self.selectedDate, perform: { date in
// Do something
})
Any ideas about the error?
Thank you.
Hello guys. I've been stuck two days with this issue, hope you can understand my question below because I'm still new with Swift.
I want to create a generic function that request some JSON data from an API, decode the response using the Codable protocol and save it in a @State variable to update the View
Here is what I've done so far.
struct Response: Codable {
var results: [Result]
}
struct Result: Codable {
var trackId: Int
var trackName: String
var collectionName: String
}
Here is the function
func loadData<T: Decodable>(model: T.Type) {
guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(model, from: data) {
DispatchQueue.main.async {
print(decodedResponse)
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}
.resume()
}
The thing is, so far I'm only able to print the response, but I can't do something like this:
DispatchQueue.main.async {
self.results = decodedResponse.results
}
Because it shows me this error Value of type 'T' has no member ' results'
Here is the View
struct TestView: View {
@State private var results = [Result]()
var body: some View {
List(results, id: \.trackId) { item in
VStack(alignment: .leading) {
Text(item.trackName)
.font(.headline)
Text(item.collectionName)
}
}
.onAppear {
loadData(model: Response.self)
}
}
// Here is the function defined
}
Somebody could give a hint? I really appreciate it
Thank you.
Dennis
Hello guys,
I trying to request some data from an API, decoded it and save the values into a @State variable in my View. I'm new with Swift, so I know that my explanation is wrong. It would be better if I show you my code:
Request function
// Request API
func request<T: Decodable>(url: String, model: T.Type, completion: @escaping (T) -> Void) {
// We take some model data T.Type
guard let url = URL(string: url) else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
do {
// Decode response with the model passed
let decodedResponse = try JSONDecoder().decode(model, from: data)
DispatchQueue.main.async {
print(decodedResponse)
completion(decodedResponse)
}
return
} catch {
print(error)
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}
.resume()
}
Model data
struct QuoteModel: Codable {
var latestPrice: Float
var changePercent: Double
}
JSON Response
{
"latestPrice": 100.01,
"changePercent": 0.02
}
View
struct Price: View {
@State var quote = QuoteModel.self
var body: some View {
Text("Hello world")
.onAppear {
request(url: endpoint, model: QuoteModel.self) { self.quote = $0 }
}
}
}
The problem is, when I try to save the results into de @State var I get this error Cannot assign value of type 'QuoteModel to type QuoteModel.Type
When the JSON response is an array of JSON, for example
[
{
"latestPrice": 100.01,
"changePercent": 0.02
},
{
"latestPrice": 50.05,
"changePercent": 0.003
}
]
I do not get this error and it works perfectly. What am I missing?
Thank you.
Dennis.
I've notice that .navigationTitle(_:) always causes layout constraints warnings. Given this example, which is in Apple documentation - https://developer.apple.com/documentation/swiftui/navigationview you can check that the layout constraint warning appears only when .navigationTitle(_:) is added. Here is the sample code:
swift
struct DestinationPageView: View {
var color: Color
var body: some View {
Text("Destination Page")
.font(.title)
.foregroundColor(color)
}
}
struct ContentView: View {
var body: some View {
NavigationView {
List {
NavigationLink(
destination: DestinationPageView(color: .purple)
) {
Text("Purple Page")
}
NavigationLink(
destination: DestinationPageView(color: .pink)
) {
Text("Pink Page")
}
NavigationLink(
destination: DestinationPageView(color: .orange)
) {
Text("Orange Page")
}
}
.navigationTitle("Title")
}
}
}
Notice that the same warning appears when I use .navigationBarTitle(_:) which is deprecated - https://developer.apple.com/documentation/swiftui/view/navigationbartitle(_:-6p1k7) by the way. This stack overflow post - https://stackoverflow.com/questions/65223457/navigationtitle-aways-creates-an-autolayout-constraint-conflict is the most recent about this issue but there is no much information. I just wondering if is something wrong with the code or it's just a bug. Is there any workaround to avoid this warning?
Hello guys, I have a quite basic question but actually I do not how to approach the problem.
Given two arrays The first one with n items
swift
arrayOfItems = ["1", "2", "3", "4", "5", "6", ..., "n"]
The second one with 5 items
swift
arrayOfFive = ["Item1", "Item2", "Item3", "Item4", "Item5"]
I want to loop over the two arrays such as the output is like:
1
Item_1
2
Item_2
3
Item_3
4
Item_4
5
Item_5
6
Item_1
7
Item_2
.
.
.
Any help is appreciated.
Dennis
Hi, I know that there are lots of questions about this topic but still I cannot find an answer. Also, I've asked Apples Copyright department but I've not received an answer yet (maybe I will never receive it). I would like to use Apple Memojis as a user avatar in my app, allowing the user to choose any avatar that he wants.
So the question is, am I allowed to use Apple Memojis in my iOS app?
Thank you.
Hello guys!
I published my first open source project to Swift Package Index and, as you know, this website builds each project to show a full compatibility report. The problem is, when my project is built in iOS to check if it's compatible with Swift 5.1 I get the following error
error: No signing certificate "iOS Development" found: No "iOS Development" signing certificate matching team ID "" with a private key was found. (in target 'StockCharts' from project 'StockCharts')
I'm still a newbie but I think it's because a Team ID is assigned to the project in Xcode, and when the server wants to build the project It needs a signing certificate, which obviously it's not in the server.
The command that the server uses to build the project is
xcrun xcodebuild -IDEClonedSourcePackagesDirPathOverride="$PWD/.dependencies" -derivedDataPath "$PWD/.derivedData" build -scheme "StockCharts" -destination "generic/platform=ios"
I think that I have to change something in the project settings but I do not what. Could you give some ideas?
Thank you.
HI there,
I've been researching for a few days whether it's possible or not to programmatically activate Dark Mode within a Swift UI Test.
Environment:
Xcode 12.5.1
What I'm trying to achieve is: I'm using Fastlane to automate screenshots, so I would like to take one screenshot per device in dark mode. I know that Fastlane supports dark mode passing the dark_mode argument, but this will take all screenshots in dark mode. I'm looking for something like this:
func testExample() throws {
let app = XCUIApplication()
setupSnapshot(app) // Set up Fastlane snapshot
app.launch()
// Take first screenshot in light mode
snapshot("1Launch")
// Do something to enable dark mode
// Take second screenshot in dark mode
snapshot("1LaunchDarkMode")
}
What I've tried so far:
func testAppleInterfaceStyleDark() {
let app = XCUIApplication()
var launchArguments: [AnyHashable] = []
launchArguments.append("-AppleInterfaceStyle")
launchArguments.append("Dark")
app.launchArguments = launchArguments as! [String]
app.launch()
}
As suggested in this Stackoverflow answer. But for me, It doesn't work.
While researching, I found lots of questions like mine but without answer. Like this one. What makes me wonder if it's impossible to do.
I would like to know if it's impossible to stop wasting time on this, or if it's possible, how can I solve it?
Thank you.
Hi there!
After a few months off, I'm starting a new app.
I'm making a TabView like this:
import SwiftUI
struct ContentView: View {
@State private var tab: Tab = .adventures
var body: some View {
TabView(selection: $tab) {
Text("Explore")
.tag(Tab.explore)
.tabItem {
Label("Explore", systemImage: "airplane.circle")
}
Text("Profile")
.tag(Tab.profile)
.tabItem {
Label("Profile", systemImage: "person")
}
}
}
enum Tab {
case explore, profile
}
}
As you noticed, I want airplane.circle and person SF Symbols on the TabView but SwiftUI is showing airplane.circle.fill and person.fill in the preview canvas and also when I run the app in the simulator.
Why it is forcing me to show those icons?
Xcode version: 13.4.1
SF Symbols version: 3.3
iOS deployment target: 15.0
Thank you.