HI,
I have an issue displaying SwiftUI previews with Xcode 14.
My project has iOS and an watchOS Target. It also includes a lot of SPM, most of them only used by the PhoneApp. The project build successfully for both iOS and watchOS.
I can see that when building the watch target, only SPM that are included in this target are build for for watchOS
The issue is when I try to build a swiftUI preview of the watch target. In this case I can see on the build for Preview log that Xcode try to build ALL spm defined in the Xcode project, including the one that are not used by the watch Target,
As a lot if spm are for iOS only, and doesn't build for watchOS, the build for preview fails, and I'm unable to preview my swiftUI views on the AppeWatch.
Note that my project is working fine on Xcode 13.
This issue is easy to reproduce in any Xcode projects containing a iOS and watchOS target by adding a SPM that is only for iOS.
Any workaround to fix this issue ?
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Posts under SwiftUI tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I recently updated my xcode and compiled my application developed in SwiftUI.
The SwiftUI List started to behave different.
List has Selection parameter for EditMode selection. However, now the list items are being selected and highlighted with grey highlighted color, even in a non-edit default mode.
Ideally, it should only select the list item in edit mode. It is how it worked before. But now when the list item is tapped in non-edit mode, it is getting selected.
Please, let me know how to make list with selection to highlight only in editmode.
import SwiftUI
struct ContentView: View {
struct Ocean: Identifiable, Hashable {
let name: String
let id = UUID()
}
private var oceans = [
Ocean(name: "Pacific"),
Ocean(name: "Atlantic")
]
@State private var multiSelection = Set<UUID>()
var body: some View {
NavigationView {
VStack {
List(oceans, selection: $multiSelection) { ocean in
Text(ocean.name)
}
.toolbar { EditButton() }
}
.padding()
.buttonStyle(PlainButtonStyle())
}
}
}
Hi everyone,
I am running into a navigation-related issue that appears to be new in iOS 16/SwiftUI 4. The code below illustrates the problem:
struct ContentView: View {
@State private var input: String = ""
var body: some View {
NavigationStack {
VStack {
Spacer()
NavigationLink("Navigate") {
Text("Nested View")
}
Spacer()
TextEditor(text: $input)
.border(.red)
.frame(height: 40)
}
.padding()
}
}
}
The initial view consists of a navigation link and a text editor at the bottom of the screen. I run the app on an iPhone (or the simulator) in iOS 16 and click on the text editor at the bottom of the screen. This invokes the virtual keyboard, which pushes up the text field. Next, I click on "Navigate" to navigate to the nested view. I navigate immediately back, which brings back the initial view without the keyboard. Unfortunately, the text field isn't pushed back to the bottom and is now located in the middle of the screen. (see attached image)
Did anyone experience similar issues? Is there a workaround I could use to force a re-layout of the initial view upon return from the navigation link?
Thanks,
Matthias
I have a small text file which I would like to share via ShareLink with watchOS. If I try to share the text file via Mail oder iMessage the recipient only receives the message without the attachment. The same code works without problems on iOS. Is the is watchOS bug?
Trying to use file importer in a swift app to upload documents into firebase Storage and getting error when running on live device but works perfectly fine on emulator.
error:
BackgroundSession <***...> Failed to issue sandbox extension for file
file:///private/var/mobile/Library/Mobile%20Documents/comappleCloudDocs/Sample.pdf, errno = [1: Operation not permitted]
UNKNOWN ERROR Error Domain=FIRStorageErrorDomain Code=-13000 "An unknown error occurred, please check the server response." UserInfo={object=Repository/Sample.pdf, ResponseBody=Can not finalize upload. Current size is 0. Expected final size is 2665098., bucket=bucket, data={length = 77, bytes = 0x43616e20 6e6f7420 66696e61 6c697a65 ... 32363635 3039382e }, data_content_type=text/plain; charset=utf-8, NSLocalizedDescription=An unknown error occurred, please check the server response., ResponseErrorDomain=com.google.HTTPStatus, ResponseErrorCode=400}
I tried separating all the logic from selectedFile.startAccessingSecurityScopedResource() all the way through the end into a function of its own using @MainActor based on another post I found around here and issue persisted..
Below is the implementation:
.fileImporter(
isPresented: $fileImporterIsPresented,
allowedContentTypes: [.pdf],
allowsMultipleSelection: false
) {
result in
switch result
{
case .success(let url):
print(url)
guard let selectedFile:URL = url.first else { return }
guard selectedFile.startAccessingSecurityScopedResource() else
{
return
}
let firebaseRepository = Storage.storage().reference().child("Repository/Sample.pdf")
let uploadTask = firebaseRepository.putFile(from: selectedFile)
uploadTask.observe(.progress)
{
snapshot in
// Upload reported progress
percentComplete = 100.0 * Double(snapshot.progress!.completedUnitCount)
/ Double(snapshot.progress!.totalUnitCount)
}
uploadTask.observe(.success)
{
snapshot in
selectedFile.stopAccessingSecurityScopedResource()
uploadTask.removeAllObservers()
print("SUCCESS")
// Upload completed successfully
}
uploadTask.observe(.failure)
{
snapshot in
if let error = snapshot.error as? NSError
{
switch (StorageErrorCode(rawValue: error.code)!)
{
case .objectNotFound:
print("NOT FOUND")
// File doesn't exist
break
case .unauthorized:
print("UNAUTHORIZED")
// User doesn't have permission to access file
break
case .cancelled:
print("CANCELLED")
// User canceled the upload
break
/* ... */
case .unknown:
print("UNKNOWN ERROR \(error.description)")
print("UNKNOWN ERROR \(error.localizedDescription)")
print("UNKNOWN ERROR \(error.underlyingErrors)")
// Unknown error occurred, inspect the server response
break
default:
print("UNSPECIFIED ERROR")
// A separate error occurred. This is a good place to retry the upload.
break
}
}
}
case .failure(let error):
print(error)
}
}
The sample code Capturing Depth Using the Lidar Camera works fine on my phone with iOS 15.6. But after upgraded the phone to iOS 16 and the Xcode to 14.0, now the sample code can only run for a few minutes on the phone and start to show the following error:
LiDARDepth[1454:256343] Execution of the command buffer was aborted due to an error during execution. Ignored (for causing prior/excessive GPU errors) (00000004:kIOGPUCommandBufferCallbackErrorSubmissionsIgnored)
Did anyone get the same error after upgrade to Xcode 14 or iOS 16. Can an expert take a look of the sample code and point out a possible solution? Thanks!
I tried the example from https://developer.apple.com/documentation/swiftui/editmode. It's not working for me.
struct ContentView: View {
@Environment(\.editMode)
private var editMode
@State
private var name = "Maria Ruiz"
var body: some View {
NavigationView {
Form {
Text(String(editMode!.wrappedValue.isEditing))
if editMode?.wrappedValue.isEditing == true {
TextField("Name", text: $name)
} else {
Text("test")
}
}
.animation(nil, value: editMode?.wrappedValue)
.toolbar { // Assumes embedding this view in a NavigationView.
EditButton()
}
}
}
}
It shows the texts "false" and "test", before and after clicking Edit. What am I missing? I'm using XCode 14.0.1 and the deployment target is iOS 16. I also tried on a real iPhone and on iOS 15.5 in the Simulator. Thanks for any help.
I like to keep my apps watch face complication up to date when the user completes an activity but calling WidgetCenter.shared.reloadAllTimelines() is not working as well as the old complication update now I want to go back to complications. I used to call CLKComplicationServer.sharedInstance().reloadTimeline(for: <#T##CLKComplication#>) which would update my complication instantly.
The simulator seams to up date widgets immediately but now my app has been released pn the App Store it is not updating.
Any one else experiencing this.
Good morning!
I am developing an iOS app that gets its data from an API and displays it in a list. The list item view has NavigationLink embedded in it that sends users to a detail view. In this detail view, I have some Text views but the issue I am running into is a WKWebView that I have implemented to display some HTML that's is retrieved from the API call.
The WKWebView displays the HTML just how I want it to. The issue I have is in the HyperLinks that are displayed in the WKWebView. When a user taps on a link, it opens inside of the web view. Instead of opening in the web view, I would like this link to open in the user's default web browser. I have searched and found ways of doing this in older versions of Swift using classes but my web view is initialized inside of a struct that conforms to the UIViewRepresentable protocol.
I don't know how to get links to open in the browser instead of the WebView so any help would be appreciated. Here is the code for my WebView that is being used on the details page.
struct NewsItemWebView: UIViewRepresentable {
// HTML from API Call
var text: String
// Method to create the View
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
// Method to update the View by changing properties of the WebView
func updateUIView(_ uiView: WKWebView, context: Context) {
uiView.isOpaque = false
uiView.backgroundColor = UIColor.white
uiView.loadHTMLString(text, baseURL: nil)
}
}
Here is how I am implementing the WebView on DetailView
NewsItemWebView(text: item.PageContent)
.frame(height: 450)
Any help on how I can make links open in a browser would be great. Thanks in advance.
I am running into an example where if you have a View that has a NavigationStack in it, and it appears and disappears based on a conditional, it doesn't seem to get fully torn down?
This appears to matter most when it is also initializing a ViewModel, because it will reinit without deiniting.
So for example
struct ContentView: View {
@State var showNavStack:Bool = false
var body: some View {
Button("ShowHide") {
showNavStack.toggle()
}.padding(20)
if showNavStack {
SimpleRootView()
}
}
}
With the NavigationStack view
import SwiftUI
class DoNothingVM:ObservableObject {
deinit {
print("ViewModel DEINIT")
}
init() {
print("ViewModel INIT")
}
}
struct SimpleRootView: View {
@StateObject var viewModel = DoNothingVM()
@State var path = NavigationPath()
let int = Int.random(in: 0...100)
var body: some View {
NavigationStack(path: $path) {
VStack {
Text("Hello \(int)")
Button("Go Forward") {
path.append(Int.random(in: 0...100))
}
}.navigationDestination(for: Int.self) { int in
DetailIntView(int: int, path: $path)
}.navigationTitle("\(int)")
}
}
}
struct DetailIntView:View {
let int:Int
@Binding var path:NavigationPath
var body: some View {
VStack {
Text("Hello \(int)")
Button("Go Forward") {
path.append(Int.random(in: 0...100))
}
}.navigationTitle("\(int)")
}
}
Will lead to multiple calls to a DoNothing init every time the showNavStack is toggled to true, but no deinit when toggled to false. Multiples remain in memory.
"So don't do that" is fine for me in my case, but I'm wondering if this is expected behavior? Is it simply that SwiftUI only expects One and Only One NavigationStack per app and that it will be the only thing in charge? I haven't tested it, but what does that mean for coming back out of the background? This seems like a bug, but it might also be my misunderstanding.
Project where I'm messing around with this here: https://github.com/carlynorama/NavigationExplorer
Is there a way to implement controls for background audio using ActivityKit like in the Apple Music application? I didn't found anything in your documentation about handling actions like this except deep links, but they're not suitable for this use case
Overview
On macOS, in a NavigationSplitView when the menu button is added to the detail view toolbar, it seems to look disabled
Environment
Xcode: 14.1 beta 3 (14B5033e)
macOS: 13.0 Beta (22A5365d)
Code:
struct ContentView: View {
@State private var selectedNumber: Int?
var body: some View {
NavigationSplitView {
List(0..<100, selection: $selectedNumber) { number in
Text("cell \(number)")
}
} detail: {
Text("Detail")
.toolbar {
ToolbarItem {
Menu {
Button("aa") {}
Button("bb") {}
} label: {
Label("Add Bookmark", systemImage: "book")
}
}
}
}
}
}
Steps to reproduce:
Run the project on macOS
Select cell 0 on the sidebar
Click on the book toolbar button and notice the menu appear
Select cell 1 on the sidebar
Expected Behaviour
After step 4, the book toolbar button should look prominent (like it is enabled)
Actual Behaviour
After step 4, the book toolbar button looks like it is disabled.
Screenshot
In the sidebar column of the NavigationSplitView I'd like to have several sections. All the items are fetched with Core Data.
View all photos (Photos entity in Core Data)
Folder (Folder entity in Core Data)
Folder A
Folder B
Folder C
Tags (Tag entity in Core Data)
Cat
Dog
In the content view, I'd like show the items based on the selection in the sidebar. I tried the following with some success but I think there should be another way of doing this.
NavigationSplitView() {
List(selection: $navigationModel.selectedCategory, content: {
NavigationLink(value: Category(type: .all, predicate: NSPredicate(value: true), title: "View all items") ) {
Text("View all items")
}
Section {
ForEach(folders){ folder in
NavigationLink(value: Category(type: .folder, predicate: NSPredicate(format: "folder == %@", folder), title: folder.name) ) {
FolderRow(folder: folder)
// ... and so on. Another section for tags
And in the content:
ZStack{
List(selection: $navigationModel.selectedPhoto) {
ContentView(photos: FetchRequest(
sortDescriptors: [sortDescriptor],
predicate: navigationModel.selectedCategory?.predicate,
animation: .default)
//....
How can refractor this code with a better solution? The problem that I'm encountering is that the selection argument in the List accepts only one type of object. But I want to select more that one type of object. Another issue is that this solution won't conform to Codable if I'm thinking correctly and reseting the app state on the next launch would be cumbersome.
I don't see the structured editing popover when I command right click on an IOS SwiftUI project when I create a new project with just "Hello World" like I see in Xcode 13. Am I missing some thing or is this a bug?
Thanks
So I have the default language of my app as Arabic so everything goes from RTL but when I changed the default language to Arabic I started encountering this issue that happens when navigating from one view to another view.
This issue shows the text inverted in a weird way.
here is the image: https://imgur.com/amI8afA
(note that this issue goes away if the TabView is not PageTabViewStyle)
I am facing out a strange behavior that really looks like a SwiftUI bug.
When I leave the app with a .sheet open and reopen it, all tappable content from parent view (such as Buttons) have an offset on tap. It is difficult to explain so here is a really simple example:
struct ContentView: View {
@State private var isOpen = false
var body: some View {
Button(action: {
isOpen.toggle()
}, label: {
Text("Open sheet")
.foregroundColor(.white)
.padding()
.background(.blue)
})
.sheet(isPresented: $isOpen, content: {
Text("Sheet content")
})
}
}
To reproduce the issue follow those steps:
Tap just below to the top border of blue button Open sheet: the sheet opens as expected.
When the sheet is open, close the app (go back to Springboard, cmd+shift+H on Simulator).
Reopen the app. You're still on the sheet view.
Close the sheet. You're back on main view with blue button. Here is the bug:
Tap again on the top of blue button, right below the top border. Nothing happens. You have to click few pixels below. There is an offset that makes all tappable items on main view (and children) not aligned.
Other notices:
When closing the app from main view, the bug doesn't appear. And even when the bug is here and I close the app from main view and reopen, the bug disappears.
If I use a .fullScreenCover instead of .sheet, the bug doesn't appear.
It really looks like a bug with .sheets open.
Expected result would be that this offset does not appear and Buttons are still tappable on their area.
Tested on Xcode 14.0 (14A309), iOS 16.0.x (Simulator and iPhone 14 Pro device) and Swift 5.
struct Item: Identifiable {
let id: String
let url = URL(string: "https://styles.redditmedia.com/t5_j6lc8/styles/communityIcon_9uopq0bazux01.jpg")!
}
struct Content: View {
let model: [Item] = {
var model = [Item]()
for i in 0 ..< 100 {
model.append(.init(id: String(i)))
}
return model
}()
var body: some View {
List(model) { item in
Row(item: item)
}
}
}
struct Row: View {
let item: Item
var body: some View {
AsyncImage(url: item.url)
}
}
Running code above with Xcode 14.1 RC on iOS 16.1 Beta simulator, AsyncImage sometimes doesn’t properly show downloaded image but grey rectangle instead when scrolling in list. Is this bug or am I missing something? Thanks
Code to reproduce:
struct CrashView: View {
var body: some View {
ScrollView {
LazyVStack {
ForEach(0...100, id: \.self) { i in
LazyVGrid(columns: Array(repeating: .init(.fixed(100)), count: 3), content: {
ForEach(0...20, id: \.self) { i in
Color.red.opacity(Double(i + 1) / 20).frame(height: 300)
}
})
}
}
}
}
}
Important: it crashes on iOS 16.1 !!!
We have 21 grid item (3 item and 7 full lines) for every LazyVStack item.
Scroll it until 5 LazyVStack item. Start scrolling to top. It blinks and show incorrect count: you see that it shows 1 item in line, but it is impossible. If you continue scrolling app crashes.
I have a class that I cannot change to ObservableObject with Published members.
I tried getting around this by writing my own Binding. Although the value is updated correctly, the UI is not. Why is this.
Below is a simple demo view. When it is run and the toggle is clicked, it will print out correctly that the value is changed, but the UI does not update. Why?
import SwiftUI
class BoolWrapper {
public var value = false {
didSet {
print("Value changed to \(value)")
}
}
}
let boolWrapper = BoolWrapper()
struct ContentView: View {
var body: some View {
Toggle(isOn: Binding(get: {
return boolWrapper.value
}, set: { value in
boolWrapper.value = value
}), label: { Text("Toggle") })
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Hi,
As you can see in the code below whenever I open the app in the normal mode app works fine and the detail view shows data properly. However, in split screen the app lost data of the selected item. I'm sure there is a bug in here unless I should manage it by myself which unacceptable!
@main
struct TestSwiftUIApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct Employee: Identifiable {
let name: String
let id: Int
}
struct ContentView: View {
@State
var selectedEmployeeId: Employee.ID?
let employess: [Employee] = [.init(name: "Hamed", id: 1), .init(name: "John", id: 2)]
var body: some View {
NavigationSplitView {
List(employess, selection: $selectedEmployeeId) { employee in
Text(employee.name)
}
} detail: {
NavigationStack {
if let employee = employess.first{$0.id == selectedEmployeeId} {
EmployeeDetails(employee: employee)
}
}
}
}
}
struct EmployeeDetails: View {
let employee: Employee
var body: some View {
Text("Detail of empolyee\(employee.name) with id: \(employee.id)")
}
}