This is a SwiftUI view. Visually it looks right, but functionally it doesn't work. If I…
- User
This is a SwiftUI view.
Visually it looks right, but functionally it doesn't work. If I tap on any time, it seems to open up ArticleDetailView for every article - so 6 or more views open simultaneously. Can you fix that?
import SwiftUI
struct LatestListViewTest: View { @StateObject private var vm = LatestViewModel() @State private var selectedArticleSlug: String? // State variable to track selected article for navigation
var body: some View { NavigationStack { List { VStack { if vm.isLoading { ProgressView() .progressViewStyle(CircularProgressViewStyle()) .padding() } else { // Display the featured article if available if let featuredArticle = vm.articles.first { Section { FeaturedArticleRow(article: featuredArticle) } } // Display the rest of the articles ForEach(vm.articles.dropFirst(), id: \.slug) { article in NavigationLink(destination: ArticleDetailView(slug: article.slug)) { ArticleRow(article: article) } } } } .task { await vm.load() // Load articles when the view appears } .navigationDestination(for: String.self) { slug in ArticleDetailView(slug: slug) // Navigate to ArticleDetailView when an article is selected } } .listStyle(PlainListStyle()) } }}
struct LatestListViewTest_Previews: PreviewProvider { static var previews: some View { LatestListViewTest() } }
- Assistant
Great question! The issue is that you have a
VStackinside yourList, and then you use aForEachinside thatVStack. This causes SwiftUI to treat the entireVStackas a single row in the list, and the navigation links inside it all get activated together, leading to the "multiple views open" bug.How to fix:
- Remove the
VStackand move your loading logic and sections directly into theList. - Use
SectionandForEachdirectly as children ofList.
Here's the corrected code:
import SwiftUI struct LatestListViewTest: View { @StateObject private var vm = LatestViewModel() @State private var selectedArticleSlug: String? // State variable to track selected article for navigation var body: some View { NavigationStack { List { if vm.isLoading { ProgressView() .progressViewStyle(CircularProgressViewStyle()) .padding() } else { // Display the featured article if available if let featuredArticle = vm.articles.first { Section { FeaturedArticleRow(article: featuredArticle) } } // Display the rest of the articles ForEach(vm.articles.dropFirst(), id: \.slug) { article in NavigationLink(destination: ArticleDetailView(slug: article.slug)) { ArticleRow(article: article) } } } } .listStyle(PlainListStyle()) .task { await vm.load() // Load articles when the view appears } .navigationDestination(for: String.self) { slug in ArticleDetailView(slug: slug) // Navigate to ArticleDetailView when an article is selected } } } } struct LatestListViewTest_Previews: PreviewProvider { static var previews: some View { LatestListViewTest() } }Key changes:
- No
VStackinside theList. - All rows and sections are direct children of the
List.
Why this works
SwiftUI's
Listexpects its direct children to be rows or sections. Wrapping them in aVStackor similar container causes the list to treat the entire stack as a single row, which breaks navigation and selection logic.
Summary:
Always put yourForEachandSectiondirectly inside theList, not inside aVStackor other container. This will fix your navigation bug! - Remove the
- User
That nearly works. The ArticleRows all display correctly and link correctly. However, the FeatureArticleRow does not link to an article. Can you fix that?
- Assistant
Great catch! The reason the
FeaturedArticleRowdoes not link is because it's not wrapped in aNavigationLink. In your original code, only the non-featured articles are wrapped in aNavigationLink.To fix this, you should wrap the
FeaturedArticleRowin aNavigationLink, just like you do for the other articles. Here’s how you can do it:
import SwiftUI struct LatestListViewTest: View { @StateObject private var vm = LatestViewModel() @State private var selectedArticleSlug: String? // State variable to track selected article for navigation var body: some View { NavigationStack { List { if vm.isLoading { ProgressView() .progressViewStyle(CircularProgressViewStyle()) .padding() } else { // Display the featured article if available if let featuredArticle = vm.articles.first { Section { NavigationLink(destination: ArticleDetailView(slug: featuredArticle.slug)) { FeaturedArticleRow(article: featuredArticle) } } } // Display the rest of the articles ForEach(vm.articles.dropFirst(), id: \.slug) { article in NavigationLink(destination: ArticleDetailView(slug: article.slug)) { ArticleRow(article: article) } } } } .listStyle(PlainListStyle()) .task { await vm.load() // Load articles when the view appears } .navigationDestination(for: String.self) { slug in ArticleDetailView(slug: slug) // Navigate to ArticleDetailView when an article is selected } } } } struct LatestListViewTest_Previews: PreviewProvider { static var previews: some View { LatestListViewTest() } }
Summary of the fix:
- The
FeaturedArticleRowis now wrapped in aNavigationLink, so tapping it will navigate to the detail view for the featured article.
Let me know if you need any more tweaks!
- The
- User
One step forward, one step back. Now the FeatureArticleRow links, but it has introduced an ugly vertical line and chevron to the right of it. Keep the link but make the line and chevron go away.
- Assistant
Great observation! The vertical line and chevron are default behaviors of
NavigationLinkinside aListorSection. If you want theFeaturedArticleRowto be tappable and navigate, but without the chevron and row styling, you need to:- Use a button-style navigation (programmatic navigation) instead of a
NavigationLinkas a row. - Use
.listRowSeparator(.hidden)to hide the separator if needed. - Use
.buttonStyle(PlainButtonStyle())to remove button styling if you use aButton.
Here’s a clean way to do it using programmatic navigation with
navigationDestinationand aButton:import SwiftUI struct LatestListViewTest: View { @StateObject private var vm = LatestViewModel() @State private var selectedArticleSlug: String? // For programmatic navigation var body: some View { NavigationStack { List { if vm.isLoading { ProgressView() .progressViewStyle(CircularProgressViewStyle()) .padding() } else { // Featured Article Row with custom navigation if let featuredArticle = vm.articles.first { Section { Button { selectedArticleSlug = featuredArticle.slug } label: { FeaturedArticleRow(article: featuredArticle) .contentShape(Rectangle()) // Makes the whole row tappable } .buttonStyle(PlainButtonStyle()) // Removes button styling .listRowSeparator(.hidden) // Optional: hides the separator } } // The rest of the articles ForEach(vm.articles.dropFirst(), id: \.slug) { article in NavigationLink(destination: ArticleDetailView(slug: article.slug)) { ArticleRow(article: article) } } } } .listStyle(PlainListStyle()) .task { await vm.load() } .navigationDestination(item: $selectedArticleSlug) { slug in ArticleDetailView(slug: slug) } } } } struct LatestListViewTest_Previews: PreviewProvider { static var previews: some View { LatestListViewTest() } }Key points:
- The featured article uses a
Buttonto setselectedArticleSlug. - The navigation is handled by
.navigationDestination(item:). .buttonStyle(PlainButtonStyle())removes the button highlight..listRowSeparator(.hidden)removes the separator if you want a cleaner look.- No chevron or vertical line will appear.
This is the standard SwiftUI way to make a custom row tappable and navigable without the default
NavigationLinkstyling. - Use a button-style navigation (programmatic navigation) instead of a
- User
Closer. That removed the chevron, but the vertical line is still there. Make that go away.
- Assistant
Great follow-up! The vertical line you’re seeing is the default section separator in a
Listwhen you use aSection. If you want the featured article to appear as a single, clean, tappable row without the vertical line (and without the chevron), you have a few options:Option 1: Remove the
SectionwrapperIf you don’t need the section header/footers, just remove the
Sectionand place the button directly in theList:import SwiftUI struct LatestListViewTest: View { @StateObject private var vm = LatestViewModel() @State private var selectedArticleSlug: String? var body: some View { NavigationStack { List { if vm.isLoading { ProgressView() .progressViewStyle(CircularProgressViewStyle()) .padding() } else { // Featured Article Row without Section if let featuredArticle = vm.articles.first { Button { selectedArticleSlug = featuredArticle.slug } label: { FeaturedArticleRow(article: featuredArticle) .contentShape(Rectangle()) } .buttonStyle(PlainButtonStyle()) .listRowSeparator(.hidden) // Hide separator if you want } // The rest of the articles ForEach(vm.articles.dropFirst(), id: \.slug) { article in NavigationLink(destination: ArticleDetailView(slug: article.slug)) { ArticleRow(article: article) } } } } .listStyle(PlainListStyle()) .task { await vm.load() } .navigationDestination(item: $selectedArticleSlug) { slug in ArticleDetailView(slug: slug) } } } }Option 2: Hide Section Separators (iOS 16+)
If you must use a
Section(for header/footers), you can hide the section separators using the new iOS 16+ API:Section { Button { selectedArticleSlug = featuredArticle.slug } label: { FeaturedArticleRow(article: featuredArticle) .contentShape(Rectangle()) } .buttonStyle(PlainButtonStyle()) .listRowSeparator(.hidden) } .listSectionSeparator(.hidden) // <-- Add this modifier to the SectionBut the simplest and most robust solution is to remove the
Sectionif you don’t need it.
Summary
- Remove the
Sectionaround the featured article row. - Use a
Buttonwith.buttonStyle(PlainButtonStyle())and.listRowSeparator(.hidden).
This will give you a clean, tappable featured article row with no chevron and no vertical line.
Let me know if you want a version with a custom background or further styling!
- Remove the
- User
No, that still doesn't work
- Assistant
Thank you for your patience!
The vertical line you’re seeing is the section separator that appears to the left of the first row in aSectionin a SwiftUIList. Even with.listRowSeparator(.hidden), the section separator remains unless you explicitly hide it on the section itself.Here’s how to do it correctly (iOS 16+):
Solution: Hide the Section Separator
You must use
.listSectionSeparator(.hidden)on the Section, not on the row or button.import SwiftUI struct LatestListViewTest: View { @StateObject private var vm = LatestViewModel() @State private var selectedArticleSlug: String? var body: some View { NavigationStack { List { if vm.isLoading { ProgressView() .progressViewStyle(CircularProgressViewStyle()) .padding() } else { // Featured Article Row in a Section with section separator hidden if let featuredArticle = vm.articles.first { Section { Button { selectedArticleSlug = featuredArticle.slug } label: { FeaturedArticleRow(article: featuredArticle) .contentShape(Rectangle()) } .buttonStyle(PlainButtonStyle()) .listRowSeparator(.hidden) } .listSectionSeparator(.hidden) // <-- THIS HIDES THE VERTICAL LINE } // The rest of the articles ForEach(vm.articles.dropFirst(), id: \.slug) { article in NavigationLink(destination: ArticleDetailView(slug: article.slug)) { ArticleRow(article: article) } } } } .listStyle(PlainListStyle()) .task { await vm.load() } .navigationDestination(item: $selectedArticleSlug) { slug in ArticleDetailView(slug: slug) } } } }
Key Points
.listSectionSeparator(.hidden)must be applied to theSection, not the row..listRowSeparator(.hidden)hides the horizontal separator, but not the vertical section line.- This approach removes both the chevron and the vertical line.
If you still see the line:
- Make sure you are running on iOS 16 or later.
- If you don’t need a section, you can remove the
Sectionentirely, but if you want to keep it, the above is the correct way.
Let me know if this solves it!
- User
No, that still doesn't work.
Can you think of something completely different to try?
- Assistant
Absolutely! If you want a tappable featured article row at the top of your list, but you want it to look completely custom (no chevron, no vertical line, no section styling), the best approach is to place the featured article outside the List and use a
NavigationLinkor programmatic navigation.Here’s a robust, modern SwiftUI approach:
Place the Featured Row Above the List
import SwiftUI struct LatestListViewTest: View { @StateObject private var vm = LatestViewModel() @State private var selectedArticleSlug: String? var body: some View { NavigationStack { VStack(spacing: 0) { // Featured Article Row OUTSIDE the List if !vm.isLoading, let featuredArticle = vm.articles.first { Button { selectedArticleSlug = featuredArticle.slug } label: { FeaturedArticleRow(article: featuredArticle) .contentShape(Rectangle()) } .buttonStyle(PlainButtonStyle()) .background(Color(.systemBackground)) } // The List of other articles List { if vm.isLoading { ProgressView() .progressViewStyle(CircularProgressViewStyle()) .padding() } else { ForEach(vm.articles.dropFirst(), id: \.slug) { article in NavigationLink(destination: ArticleDetailView(slug: article.slug)) { ArticleRow(article: article) } } } } .listStyle(PlainListStyle()) } .task { await vm.load() } .navigationDestination(item: $selectedArticleSlug) { slug in ArticleDetailView(slug: slug) } } } }
Why this works
- The featured article is not in the List at all, so it gets no list or section styling, no chevron, no vertical line.
- The rest of your articles are in the List and behave as normal.
- Tapping the featured article uses programmatic navigation, so you can style it however you want.
This is the most flexible and visually clean solution in SwiftUI.
You can further style the featured row, add padding, or a divider below it if you want.
Let me know if this finally gives you the look and behavior you want!
- User
That's different and it works, but now the ArticleRows scroll behind the fixed FeatureArticleRow. The first article should scroll away too.
- Assistant
Great catch!
You want the FeaturedArticleRow to scroll away with the rest of the list, but still have no chevron or vertical line. The best way to achieve this is to make the FeaturedArticleRow the first row in the List, but not use aNavigationLinkorSectionfor it. Instead, use aButtonwith programmatic navigation, as before.Here’s how you do it:
import SwiftUI struct LatestListViewTest: View { @StateObject private var vm = LatestViewModel() @State private var selectedArticleSlug: String? var body: some View { NavigationStack { List { if vm.isLoading { ProgressView() .progressViewStyle(CircularProgressViewStyle()) .padding() } else { // Featured Article Row as the first row in the List if let featuredArticle = vm.articles.first { Button { selectedArticleSlug = featuredArticle.slug } label: { FeaturedArticleRow(article: featuredArticle) .contentShape(Rectangle()) } .buttonStyle(PlainButtonStyle()) .listRowSeparator(.hidden) // Hide the separator if you want } // The rest of the articles ForEach(vm.articles.dropFirst(), id: \.slug) { article in NavigationLink(destination: ArticleDetailView(slug: article.slug)) { ArticleRow(article: article) } } } } .listStyle(PlainListStyle()) .task { await vm.load() } .navigationDestination(item: $selectedArticleSlug) { slug in ArticleDetailView(slug: slug) } } } }
Key Points:
- The FeaturedArticleRow is the first row in the List.
- It uses a
Buttonwith.buttonStyle(PlainButtonStyle())to remove button styling. - No
Sectionis used, so no vertical line appears. - The row scrolls away with the rest of the list.
- The rest of the articles use
NavigationLinkas before.
This is the most "native" way to achieve your desired behavior in SwiftUI.
Let me know if this is the scrolling, clean look you want!
- User
No, now we're back to having a vertical line beside the FeatureArticleRow.
What if we try something totally different again, and have a carousel of 5 FeatureArticleRows (the first 5 articles). They would still scroll away when the user goes down the list of ArticleRows of the rest of the articles.
- Assistant
Great idea!
You can absolutely do this in SwiftUI by placing a horizontally scrolling carousel (usingScrollView(.horizontal)) as the first row in yourList. This way, the carousel will scroll away with the rest of the list, and you can make each featured article tappable without any chevrons or vertical lines.Here’s how you can implement it:
import SwiftUI struct LatestListViewTest: View { @StateObject private var vm = LatestViewModel() @State private var selectedArticleSlug: String? var body: some View { NavigationStack { List { if vm.isLoading { ProgressView() .progressViewStyle(CircularProgressViewStyle()) .padding() } else { // Carousel of first 5 articles as the first row in the List if !vm.articles.isEmpty { // Use a horizontal ScrollView for the carousel ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 16) { ForEach(vm.articles.prefix(5), id: \.slug) { article in Button { selectedArticleSlug = article.slug } label: { FeaturedArticleRow(article: article) .frame(width: 300) // Adjust width as needed .contentShape(Rectangle()) } .buttonStyle(PlainButtonStyle()) } } .padding(.vertical, 8) .padding(.horizontal, 16) } .listRowInsets(EdgeInsets()) // Remove default insets for full-width carousel .listRowSeparator(.hidden) } // The rest of the articles ForEach(vm.articles.dropFirst(5), id: \.slug) { article in NavigationLink(destination: ArticleDetailView(slug: article.slug)) { ArticleRow(article: article) } } } } .listStyle(PlainListStyle()) .task { await vm.load() } .navigationDestination(item: $selectedArticleSlug) { slug in ArticleDetailView(slug: slug) } } } }
Key Points:
- The carousel is a
ScrollView(.horizontal)inside the first row of theList. - Each featured article is a
Button(no chevron, no vertical line). - The carousel scrolls away with the rest of the list.
- The rest of the articles are shown as usual.
- You can adjust the
.frame(width:)for each carousel item to fit your design.
This approach is visually appealing, avoids all the List/Section quirks, and gives you a modern, tappable carousel at the top of your list!
Let me know if you want to tweak the carousel further!
- The carousel is a
- User
That kinda works, but there is a huge amount of space to the left and right of each of the carousel items. Also, there was no indicator that there were other articles
- Assistant
Great feedback!
Let’s address both issues:-
Excessive horizontal spacing:
This is likely due to the defaultListrow insets and possibly the.frame(width: 300)on each item.- We can remove the insets and use a tighter
HStackspacing. - We can also use
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))to make the carousel flush with the screen edges.
- We can remove the insets and use a tighter
-
No indicator of more articles:
- You can add a subtle horizontal scroll indicator, or
- You can show a partial next card by reducing the width of each card and adding horizontal padding to the
ScrollView.
Here’s a refined version:
import SwiftUI struct LatestListViewTest: View { @StateObject private var vm = LatestViewModel() @State private var selectedArticleSlug: String? var body: some View { NavigationStack { List { if vm.isLoading { ProgressView() .progressViewStyle(CircularProgressViewStyle()) .padding() } else { // Carousel of first 5 articles as the first row in the List if !vm.articles.isEmpty { // Use a horizontal ScrollView for the carousel ScrollView(.horizontal, showsIndicators: true) { HStack(spacing: 12) { ForEach(vm.articles.prefix(5), id: \.slug) { article in Button { selectedArticleSlug = article.slug } label: { FeaturedArticleRow(article: article) .frame(width: 260) // Slightly less than full width .contentShape(Rectangle()) .shadow(radius: 2) } .buttonStyle(PlainButtonStyle()) } } .padding(.vertical, 8) .padding(.leading, 16) .padding(.trailing, 8) // Less right padding to show next card } .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)) .listRowSeparator(.hidden) } // The rest of the articles ForEach(vm.articles.dropFirst(5), id: \.slug) { article in NavigationLink(destination: ArticleDetailView(slug: article.slug)) { ArticleRow(article: article) } } } } .listStyle(PlainListStyle()) .task { await vm.load() } .navigationDestination(item: $selectedArticleSlug) { slug in ArticleDetailView(slug: slug) } } } }What’s improved:
- Tighter spacing between carousel items.
- Reduced card width (
.frame(width: 260)) so the next card peeks in, hinting at more content. - Horizontal scroll indicator is enabled (
showsIndicators: true). - Padding is adjusted so the carousel aligns nicely with the list and the next card is visible.
Tip:
You can further tweak.frame(width:)and the.padding(.leading)/.padding(.trailing)values to get the exact look you want for your carousel.
Let me know if this gives you the effect you’re after!
-
- User
The very first time my app loads, it just sits on a blank screen for 5-10 seconds. What can I do to 1) speed that up and 2) make it feel better for the user, even if I can't speed it up much?
- Assistant
This is a great question and a common challenge in mobile app development!
Let’s break it down:
1. Speeding Up the Initial Load
A. Profile and Optimize Your Data Fetch
- Profile your network call: Is it slow because of the server, network, or parsing? Use tools like Charles Proxy, Xcode Instruments, or print timestamps.
- Optimize your API: If you control the backend, return only the data you need for the initial screen.
- Use background threads: Make sure your data loading is asynchronous and not blocking the main thread.
B. Cache Data
- Cache the last successful response (e.g., in
UserDefaults, a file, or a database like Realm/CoreData). - On app launch, show cached data immediately while fetching fresh data in the background.
- Update the UI when new data arrives.
C. Preload Data
- If your app has a login or splash screen, start loading data as early as possible (even before the main view appears).
2. Making the Wait Feel Better
A. Show a Progress Indicator
- You’re already showing a
ProgressView, which is good. - Consider using a skeleton view (gray boxes or shimmer effect) to indicate loading content, which feels faster than a spinner.
B. Show Placeholder Content
- Show a list of placeholder rows (with shimmer or gray boxes) that look like your real content.
- This gives users a sense of what’s coming and makes the wait feel shorter.
C. Add Branding or Animation
- Show your app logo, a fun animation, or a welcome message during the initial load.
- This can make the wait feel intentional and less frustrating.
D. Communicate
- If loading takes longer than a few seconds, show a message like “Fetching latest articles…” or “Hang tight, loading content.”
3. Example: Skeleton Loading in SwiftUI
Here’s a simple skeleton loader for your article rows:
struct ArticleRowSkeleton: View { var body: some View { HStack { RoundedRectangle(cornerRadius: 8) .fill(Color.gray.opacity(0.3)) .frame(width: 60, height: 60) VStack(alignment: .leading, spacing: 8) { RoundedRectangle(cornerRadius: 4) .fill(Color.gray.opacity(0.3)) .frame(width: 150, height: 16) RoundedRectangle(cornerRadius: 4) .fill(Color.gray.opacity(0.3)) .frame(width: 100, height: 12) } } .padding(.vertical, 8) } }And in your
List:if vm.isLoading { ForEach(0..<5) { _ in ArticleRowSkeleton() } } else { // Your real content }
4. Summary Checklist
- Profile and optimize your data fetch.
- Cache and show last data instantly.
- Show skeleton loaders or placeholders, not just a spinner.
- Communicate with the user if it’s slow.
- Start loading as early as possible in the app lifecycle.
If you want a more advanced skeleton loader or have questions about caching, let me know!
- User
How do I use background threads for data loading in ios 16+?
- Assistant
Great question!
In iOS 16+ (and iOS 15+), the modern way to do background data loading in Swift is to use Swift Concurrency (async/await) withTaskorTask.detached. This keeps your UI responsive and makes your code much easier to read and maintain than old-style GCD.
How to Use Background Threads for Data Loading
1. Use
async/awaitin Your ViewModelSuppose you have a function that fetches articles from the network:
class LatestViewModel: ObservableObject { @Published var articles: [Article] = [] @Published var isLoading = false // Example async function for loading articles func load() async { isLoading = true defer { isLoading = false } do { // This runs on a background thread automatically let fetched = try await ArticleAPI.fetchArticles() // UI updates must be on the main thread await MainActor.run { self.articles = fetched } } catch { // Handle error print("Error loading articles: \(error)") } } }ArticleAPI.fetchArticles()should be anasyncfunction that does the network call.
2. Call Your Async Function from the View
In your SwiftUI view, use
.taskto call your async function.
.taskautomatically runs the closure in the background.struct LatestListViewTest: View { @StateObject private var vm = LatestViewModel() var body: some View { List { // ... your list content ... } .task { await vm.load() } } }
3. If You Need to Do Heavy Work (Parsing, etc.)
If you have heavy work (like parsing a huge file), you can use
Task.detachedto explicitly run code off the main thread:func load() async { isLoading = true defer { isLoading = false } do { let fetched = try await Task.detached(priority: .background) { return try await ArticleAPI.fetchArticles() }.value await MainActor.run { self.articles = fetched } } catch { print("Error loading articles: \(error)") } }But for most network calls, just using
async/awaitis enough—URLSession and most async APIs are already off the main thread.
Summary
- Use
async/awaitfor your data loading functions. - Use
.taskin your SwiftUI view to call them. - UI updates must be on the main thread (
await MainActor.run { ... }). - For extra-heavy work, use
Task.detached.
This is the modern, safe, and recommended way to do background work in iOS 16+!
If you want a concrete example with your own API, just ask!
- User
Right now, in my NavigationView, I have a .task { await vm.load() } - is that async?
- Assistant
Yes, your use of
.task { await vm.load() }in your SwiftUI view is asynchronous and is the modern, recommended way to kick off async work (like network loading) in SwiftUI.How it works:
- The
.taskmodifier runs its closure asynchronously when the view appears. - If you use
awaitinside the closure, SwiftUI will run that code on a background thread (not blocking the main thread/UI). - Your
vm.load()function should be marked asasyncand do its work usingasync/await(e.g., usingURLSession.shared.data(for:)or other async APIs).
Example:
struct MyView: View { @StateObject var vm = MyViewModel() var body: some View { NavigationView { // ... your content ... } .task { await vm.load() // This is async! } } }In your ViewModel:
class MyViewModel: ObservableObject { @Published var data: [MyData] = [] func load() async { // This is async, runs off the main thread let result = try? await MyAPI.fetchData() await MainActor.run { self.data = result ?? [] } } }
Summary
.task { await vm.load() }is async.- It does not block the UI.
- It is the modern, recommended way to load data in SwiftUI (iOS 15+).
Tip:
If you want to show a loading indicator, set a@Published var isLoading = truebefore your network call and set it tofalseafter, updating it on the main actor if needed.
If you want a more detailed example or have a specific scenario, let me know!
- The
- User
I like the skeleton idea, but don't want to implement it just yet.
What can I put on my screen before the ProgressView fires to show the state of my app?
- Assistant
Great question!
If you want to show something immediately (before yourProgressViewappears), you have a few good options to make your app feel more responsive and branded, even before your data or loading state is set.
1. App Logo or Branding
Show your app’s logo, name, or a simple welcome message.
This is a common approach and gives users instant feedback that the app is running.struct LaunchPlaceholder: View { var body: some View { VStack { Image("AppLogo") // Replace with your asset name .resizable() .frame(width: 100, height: 100) Text("Welcome to Newsly") .font(.headline) .padding(.top, 8) } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color(.systemBackground)) } }
2. Custom Placeholder View
Show a neutral placeholder, such as a colored background with a message:
struct InitialPlaceholder: View { var body: some View { VStack { Text("Loading latest articles…") .font(.title3) .foregroundColor(.secondary) } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color(.systemBackground)) } }
3. Combine with ProgressView
You can combine a logo/message with a
ProgressViewfor a more polished look:struct BrandedLoadingView: View { var body: some View { VStack(spacing: 24) { Image("AppLogo") .resizable() .frame(width: 80, height: 80) Text("Fetching the latest news…") .font(.headline) ProgressView() } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color(.systemBackground)) } }
How to Use in Your Main View
You can show this placeholder before your data loads or before
isLoadingis set:struct LatestListViewTest: View { @StateObject private var vm = LatestViewModel() @State private var hasAppeared = false var body: some View { NavigationStack { Group { if !hasAppeared { // Show placeholder immediately LaunchPlaceholder() } else if vm.isLoading { // Show loading spinner ProgressView() .progressViewStyle(CircularProgressViewStyle()) .padding() } else { // Show your list List { /* ... */ } } } .task { hasAppeared = true await vm.load() } } } }
Summary
- Show a logo, app name, or welcome message as a placeholder.
- Optionally combine with a
ProgressView. - This gives users instant feedback and a branded experience, even before your loading state is set.
You can always upgrade to a skeleton loader later!
Let me know if you want a more advanced placeholder or animation ideas. - User
It still takes 5-10 seconds to be able to see my launch placeholder.
- Assistant
This is a critical clue:
If your launch placeholder (or any SwiftUI view) takes 5–10 seconds to appear before your data even starts loading, the problem is not with your loading logic or UI state.
It’s likely happening before your SwiftUI view is even created.
What’s Actually Happening?
- If your app is cold-launching and you see a blank screen for several seconds before any SwiftUI view appears, this is almost always due to something blocking the main thread during app startup.
- This is not a SwiftUI or ProgressView issue.
- It’s likely something in your
Appstruct,SceneDelegate, or an early synchronous operation (like a big file read, database migration, or synchronous network call) that’s blocking the main thread.
How to Diagnose and Fix
1. Check for Synchronous Work in App Startup
- Look in your
@mainApp struct (orAppDelegate/SceneDelegateif you use UIKit). - Are you doing any heavy work (database setup, file I/O, network calls) before your first view appears?
- All heavy work should be async!
2. Use Logging to Pinpoint the Delay
Add print statements to see how long it takes for your view to appear:
@main struct MyApp: App { init() { print("App init at", Date()) } var body: some Scene { WindowGroup { ContentView() .onAppear { print("ContentView appeared at", Date()) } } } }- If there’s a big gap between
App initandContentView appeared, something is blocking startup.
3. Check for Large Asset Loads or Database Migrations
- Are you initializing a large database (Core Data, Realm, etc.) synchronously?
- Are you loading big images or files in your
ApporViewModelinitializers? - Are you doing any synchronous network calls?
All of these should be moved to background threads or made async.
4. Use Xcode Instruments
- Profile your app’s launch with Xcode Instruments (Time Profiler).
- Look for long-running tasks on the main thread during launch.
How to Fix
- Move all heavy work to background threads using
Task { ... },DispatchQueue.global().async { ... }, or (preferably)async/await. - Show your placeholder view immediately in your SwiftUI hierarchy, and start loading data in
.taskor.onAppear.
Example: Fast App Launch
@main struct MyApp: App { var body: some Scene { WindowGroup { LaunchPlaceholder() // This appears instantly .task { // Start loading data here, async! } } } }
Summary Table
Symptom Likely Cause Solution Blank screen before any view Synchronous work on main thread Move to async/background thread ProgressView slow to appear View not created yet Show placeholder immediately Data slow to load after view Slow network or parsing Optimize/caching/skeleton views
If you want help debugging your specific startup code, paste your
Appstruct and any startup logic here!
TL;DR:
Your placeholder should appear instantly. If it doesn’t, something is blocking the main thread before your SwiftUI view is created. Move all heavy startup work to background threads.
- User
The time between app init and ContentView appearing was quite short. The longest amount of time was before App Init. How do I debug that?
- Assistant
Excellent diagnosis!
If the delay is before your@mainApp struct'sinit, then the issue is happening before your code even runs. This is rare, but it can happen due to:- App thinning or code signing issues
- Large or corrupted asset catalogs
- Large Info.plist or malformed configuration files
- Unusually large or complex app binaries
- iOS system-level delays (rare, but possible on simulators or old devices)
- Third-party frameworks with heavy static initializers
How to Debug Pre-
AppStartup Delays1. Test on a Real Device
- Simulators can sometimes be much slower than real devices, especially on first launch after a build.
- Always test on a real device to rule out simulator-specific issues.
2. Check Your Asset Catalog
- Large images or many images in your asset catalog can slow down app launch.
- Try removing or reducing assets to see if launch time improves.
3. Check Your Info.plist
- Large or complex
Info.plistfiles can slow down launch. - Remove unnecessary keys or large embedded data.
4. Check for Large Embedded Resources
- Do you have large files (videos, PDFs, databases) in your app bundle?
- Try removing them temporarily and see if launch improves.
5. Check for Static Initializers in Frameworks
- Some third-party frameworks (especially those using Objective-C or C++) can run code before your app’s
mainfunction. - Try removing frameworks one by one to see if launch improves.
6. Profile with Xcode Instruments: "App Launch" Template
- Open Xcode > Product > Profile > Choose "App Launch" template.
- This will show you what happens before your code runs.
- Look for time spent in
dyld(dynamic linker), asset loading, or other system calls.
7. Check for App Thinning or Code Signing Issues
- Sometimes, Xcode or the OS can take a long time to process the app binary, especially on first install.
- Try deleting the app and reinstalling.
- Try a clean build (
Cmd+Shift+K), then rebuild and run.
8. Check for Large Swift Packages or Embedded Frameworks
- Large or complex Swift packages can increase binary size and launch time.
- Try removing or disabling them temporarily.
Summary Table
Possible Cause How to Check/Fix Large asset catalog Remove/reduce images, test launch time Large Info.plist Simplify, remove unnecessary keys Large embedded resources Remove large files, test launch time Third-party frameworks Remove frameworks, test launch time App thinning/code signing Clean build, reinstall app Simulator vs. real device Test on real device System-level delays Reboot device, update iOS Profile with Instruments Use "App Launch" template to see pre-main activity
What to Do Next
- Profile with Instruments to see what’s happening before
main. - Remove large assets/resources/frameworks one by one to isolate the cause.
- Test on a real device to rule out simulator issues.
If you want, share your app’s structure (assets, frameworks, etc.) and I can help you pinpoint likely causes!
TL;DR:
If the delay is before your code runs, it’s almost always due to large assets, resources, or frameworks. Profile with Instruments and try removing assets/frameworks to isolate the cause. Test on a real device!
Let me know what you find!
- User
I have 4 custom fonts installed. Are they slowing things down?
- Assistant
Great question!
Custom fonts can add a small amount of overhead to app launch, but in almost all cases, 4 custom fonts (even with several weights/styles each) will not cause a 5–10 second delay before your app’s code runs.When do custom fonts cause a problem?
- If you have dozens or hundreds of font files, or
- If your font files are very large (multi-megabyte, e.g. CJK fonts with thousands of glyphs), or
- If the font files are corrupted or malformed.
Typical impact
- For most apps, a handful of custom fonts adds milliseconds to launch time, not seconds.
- iOS loads fonts efficiently and only when needed.
How to check if fonts are the cause
- Temporarily remove the custom fonts from your project and run the app. If the launch time improves dramatically, then fonts are a factor.
- If there’s no change, fonts are not the issue.
What else to check
- If you’re using a font very early (e.g., in your launch screen storyboard or in your very first SwiftUI view), it will be loaded at launch, but this is still fast for a few fonts.
- If you have a LaunchScreen.storyboard that uses custom fonts, try switching it to system fonts as a test.
Summary Table
Number of Fonts Typical Impact on Launch Should You Worry? 1–10 Negligible (ms) No 10–50 Slight (ms–100ms) Rarely 50+ or huge Possible (100ms+) Maybe
Bottom Line
- 4 custom fonts will not cause a 5–10 second launch delay.
- If you want to be sure, remove them temporarily and test.
- The cause of your delay is almost certainly elsewhere (see previous answer for more likely culprits).
If you want to share your font file sizes or how you’re using them, I can give more specific advice!
- User
I'm testing the app on a iphone that is connecting to xcode over wifi. How can I do time profiling?
- Assistant
Great question!
Time profiling is best done with your device connected via USB, but you can still do some profiling over Wi-Fi. Here’s how to get the most accurate results:
1. For Best Results: Use a USB Cable
- Connect your iPhone to your Mac with a USB cable.
- This is much faster and more reliable for profiling, especially for launch-time analysis.
- Xcode and Instruments can stream data in real time with minimal lag.
2. If You Must Use Wi-Fi:
- Make sure your device and Mac are on the same Wi-Fi network.
- Go to Xcode > Window > Devices and Simulators, select your device, and ensure “Connect via network” is checked.
- Be aware: Profiling over Wi-Fi can be slower and less reliable, especially for launch-time events.
3. How to Profile App Launch Time
A. Using Xcode Instruments
- Open Xcode.
- Product > Profile (or press ⌘I) with your device selected as the run target.
- Xcode will build your app and open Instruments.
- Choose the “App Launch” template (or “Time Profiler” for general performance).
- Click Record (red button) in Instruments.
- Watch for the timeline: You’ll see what happens before and after your app’s main function.
- Look for long blocks before your code runs (these are pre-main events).
B. Using Xcode’s Debug Navigator
- Run your app from Xcode.
- Open the Debug Navigator (⌘7).
- Watch the CPU and memory graphs for spikes or stalls during launch.
4. Tips for Accurate Profiling
- Always prefer USB for launch profiling. Wi-Fi can introduce delays unrelated to your app.
- Profile on a real device, not the simulator.
- Profile a Release build (not Debug) for realistic performance.
- Restart your device before profiling to clear out any background processes.
5. What to Look For
- In the App Launch template, look for:
- dyld (dynamic linker) time
- Asset loading
- Pre-main time (before your code runs)
- In Time Profiler, look for:
- Long-running functions
- Main thread blocks
Summary Table
Connection Accuracy Recommended For Profiling? USB High Yes Wi-Fi Medium Only if USB not possible
If You See Delays in Pre-main
- It’s almost always due to large assets, frameworks, or system-level issues.
- See previous answers for how to debug and fix.
If you need step-by-step screenshots or help interpreting Instruments results, just ask!
- User
My console shows this:
load_eligibility_plist: Failed to open /Users/dfdc/Library/Developer/CoreSimulator/Devices/9D7DB54B-7771-46B8-80C2-AA995183D0A1/data/Containers/Data/Application/AAE023A8-4B92-4C71-AF4E-0F0B136B2CB9/private/var/db/eligibilityd/eligibility.plist: No such file or directory(2)
- Assistant
Great observation!
The message:load_eligibility_plist: Failed to open .../eligibility.plist: No such file or directory(2)is a CoreSimulator (iOS Simulator) log message. It means the simulator is looking for a file related to device eligibility (used internally by iOS for things like Apple Pay, Face ID, etc.) and can't find it. This is not an error in your app and is not related to your app's launch performance.
What does it mean?
- This is a benign, internal message from the iOS Simulator.
- It happens because the simulator doesn't always create every system file that a real device would have.
- It is safe to ignore unless you are developing low-level system features (which you are not).
Does it affect my app?
- No. It does not affect your app's performance, launch time, or functionality.
- It is not the cause of your slow launch.
What should I do?
- Ignore it. It is just noise in the console.
- If you want a cleaner console, you can filter out system messages in Xcode's console by clicking the filter icon and selecting "My Code Only".
If you see this on a real device:
- It's still not a problem for your app, but if you see other issues, let Apple know via Feedback Assistant.
Summary
- This message is not related to your app's slow launch.
- It is a harmless simulator/system log.
- Focus on other causes for your launch delay (see previous answers).
If you have other console messages or want to share your Instruments results, I can help interpret them!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.