SwiftUI, Alert disrupts NavigationLink? - swiftui

previous threads on this question have non-swift answers that I can't figure out how to implement in SwiftUI. Please note that I'm using Xcode 12.5.
I created a playground in an attempt to post a "demo" version of the code, but wouldn't you know it, the playground runs flawlessly. So, going to post little bits of the code without making your eyes bleed. I'm getting this warning:
pushViewController:animated: called on <TtGC7SwiftUI41StyleContextSplitViewNavigationControllerVS_19SidebarStyleContext 0x103021c00> while an existing transition or presentation is occurring; the navigation stack will not be updated.
Here's how the code operates:
Navigate from View A to View B. In View A's NavigationLink, I run this:
NavigationLink(destination: MainScreen(user: user)) {
CapsuleButtonView(txt: "LOGIN")
}.simultaneousGesture(TapGesture().onEnded {
user.login()
})
.padding([.leading, .bottom, .trailing])
user.login() checks to see if the username and password are entered (bindings). If not, it flips a #Published Bool which the view that runs the above code uses to trigger the alert message:
.alert(isPresented: $user.alert, content: {
Alert(title: Text("Message"), message: Text(user.alertMsg), dismissButton: .destructive(Text("Ok")))
})
The Alert pops as it should, but I think it does it after the NavigationLink has started to navigate away from View A to View B. So, after the Alert pops, the NavigationLink's simultaneousGesture block still runs the code in it (I checked with print statement), but does NOT navigate to View B.
Thanks for your help guys. After 3 days of looking a this, I'm about to tear out what little hair I have left.

Try adding navigationViewStyle(.stack)
NavigationView {
//Your view
}
.navigationViewStyle(.stack)

Related

#EnvironmentObject disappearing when used on modal sheet

There seems to be a bug in #SwiftUI where #EnvironmentObject will be no longer available if the user pulls down a modal sheet to close it, but cancels the gesture leaving it open.
Actual error:
SwiftUI:0: Fatal error: No ObservableObject of type found. A View.environmentObject(_:) for may be missing as an ancestor of this view.
It doesn't happen all the time, but finding it not too hard to reproduce. Does anyone know of a fix?
Just append a .environmentObject(env) to the presented sheet and it fixes your problem.
In more detail:
#EnvrironmentObject var currentEnvironment: SomeEnvironment
#State var isSheetPresented: Bool = false
var body: some View {
VStack {
// ...
}
.sheet(isPresented: $isSheetPresented) {
OtherView()
.environmentObject(currentEnvironment)
}
}
To reproduce the issue, you can use the drag gesture to drag the sheet halfway to close it, and just release it. (in a way that it does not close...)
About the situation, I once read that it is somehow a bug. But I also read that this is intended. To me, it seems that it is a bug because the condition that it happens in, feels not right to me.

Can't catch bluetooth headset button click event in swiftui 2.0

I am trying to simply execute code on a click of a bluetooth headset button in a SwiftUI 2.0 app, but after trying many different codes, nothing have worked... Does someone have solved this issue?
Based on apple docs and some answer I found on StackOverflow (https://stackoverflow.com/a/58249502/13207818), I tried this simple code
import SwiftUI
import MediaPlayer
struct ContentView: View {
init() {
MPRemoteCommandCenter.shared().pauseCommand.isEnabled = true
MPRemoteCommandCenter.shared().pauseCommand.addTarget(handler: { (event) in
print("Pause")
return MPRemoteCommandHandlerStatus.success
})
MPRemoteCommandCenter.shared().playCommand.isEnabled = true
MPRemoteCommandCenter.shared().playCommand.addTarget(handler: { (event) in
print("Play")
return MPRemoteCommandHandlerStatus.success
})
MPRemoteCommandCenter.shared().togglePlayPauseCommand.addTarget (handler: { (event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus in
// middle button (toggle/pause) is clicked
print("event:", event.command)
return .success
})
}
var body: some View {
Text("Hello World")
}
}
Of course Enabling Background Audio as per Apple doc
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
Even tried to activate my app audio session:
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord, mode: .default, options: [.duckOthers, .allowBluetooth, .allowBluetoothA2DP])
try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
print("audioSession is Active")
} catch {
print("audioSession properties weren't set because of an error.")
print(error)
}
But everything failed...
Would someone know what I am doing wrong or would have faced such issue with swiftUI 2.0?
Thank in advance for your support
In general you shouldn’t do actions in the initializers of views. Since they represent the state of the UI, not the actual UI they could be broken down and created again whenever SwiftUI thinks it needs to.
Im not at my pc but You can probably get a Publisher for the pause button which you can bind to a view with onReceive
Finally, I got a solution for my issue.
I don't know how it works really behind but the audio focus wasn't on my app. So I've just played a silent sound for a second and I could play properly with my play/pause button. I know that it's not a proper solution, but it works!
This reminds me of a similar bug on the galaxy s8...
If I find a better one, I'll keep you posted.

SwiftUI SecureField: How to achieve the same character obscuring behaviour as in UIKit?

My problem is SecureField in SwiftUI doesn’t display characters input by the user for any time at all, it just directly shows the '•' symbol for each character as it's typed - whereas in UIKit, UITextField (with isSecureTextEntry = true) shows the latest character for a second before hiding it behind '•'.
UX testers at my company have requested I bring back the "old behaviour" - but this behaviour doesn't seem part of any public API.
Interestingly this goes for UITextField custom classes injected into SwiftUI using UIViewRepresentable too - they behave in the "SwiftUI way" described above. So there's some contextual behaviour modification going on in SwiftUI for all secure UITextField behaviour? I'd have to completely rewrite my SwiftUI form into a full UIViewController to get back the behaviour (modally pushed UIViewControllers with secure UITextFields do exhibit the desired behaviour.)
Is this a sort of sideline bug in SwiftUI? I see the same thing for SwiftUI in both iOS13 and 14. Anyone seen a workaround or solution?
-EDIT-
After #Asperi's great explanation below, I noticed that my UITextField custom classes injected into SwiftUI using UIViewRepresentable were forcing this behaviour by unnecessarily setting the text binding in the updateUIView call. Using a Coordinator only to deal with text logic fixed the problem for me when using this method.
The observed effect is due to immediate apply to bound string state and immediate react/rebuild of view.
To bring desired behavior beck we need to postpone somehow state update and thus give a chance for SecuredField/UITextField to update self without synchronisation with state.
Here is a demo of possible direction (it is not ideal, but a way to go). Tested with Xcode 12.1 / iOS 14.1.
struct DemoSecureFieldView: View {
#State private var password = "demo"
var textBinding: Binding<String> {
Binding(get: { password },
set: { value in
// more logic can be added to delay _only_ if new symbol added,
// and force apply if next symbol came fast
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
password = value
}
}
)
}
var body: some View {
VStack {
SecureField("Placeholder", text: textBinding)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
}.background(Color.pink)
}
}

iOS 14 AssistiveTouch Dwell Control sometimes not working on SwiftUI Buttons

I have a SwiftUI App which uses regular Button views and our customers use AssistiveTouch's DwellControl feature quite often. On iOS 13 DwellControl was working fine but on iOS 14 beta 8 DwellControl fails to be able click on those buttons.
The Buttons can be tapped by finger and clicked with the normal mouse but not with the DwellControl feature.
I have tried adding accessibility traits like isButton, but nothing works.
Has anyone encountered the same problem and has a solution or any insight at all? I know this is quite niche but any help is appreciated!
EDIT:
I have tested it with a very simple example, including one a Button and it works fine. It seems to be a side effect of some sorts in my specific App.
I have several ZStacks which show and hide some views like modals and popovers. Could this be the source of failure?
What I don't get is that the Buttons can be tapped and clicked... If a view was blocking the Button then this shouldn't be possible right?
I have tried Release and Debug builds which does not make a difference.
When DwellControl is activated and the cursor is on the Button that shall be clicked, tapping doesn't work either. But when the cursor is nowhere near the Button, tapping works fine.
I have send a report via Feedback to Apple.
EDIT:
I found the cause. ScrollView somehow prevents all DwellControl clicks from happening. That happens whenever a ScrollView is somewhere present in one of the Views.
Minimal example:
struct ContentView: View {
#State var show = false
var body: some View {
ZStack {
ScrollView {
Button(action: {
print("This should be printed but isn't....")
}, label: {
Text("Button in ScrollView")
})
}
}
}
}
I know its niche but maybe someone needs this.
There are other components which are affected and cause the same behaviour:
ScrollView
TextField
Slider
Stepper
UIViewRepresentable
For me this is a big issue, since our customers use DwellControl quite often.
EDIT:
This can be replicated in the newest iOS 14.2 beta 1:
import SwiftUI
#main
struct TempSwitUIApp: App {
#State private var text: String = "I am a text"
var body: some Scene {
WindowGroup {
Button(action: {
print("\(UUID()) \(self.text)")
}, label: {
Text("Print text to the console")
})
TextField("Hello", text: self.$text)
}
}
}
I updated my issue with Apple but haven't heard from them yet.

Hide statusbar in swift ui, when .statusbar(hidden: true) does not work or react

I have an app that loads a tabbar with a view as initial screen, RecipeList(). Inside of RecipeList I call another view to show a recipe full screen. In RecipeList file I have code to show or hide the status bar checking if the recipe detail fullscreen view is loaded or not. It works perfectly if I preview it in xcode, BUT when I preview the code below, which is my Home() view file, and what I want to load as initial screen due to tabbar need, THEN the code inside of RecipeList to show or hide statusbar doesnt work anymore, and status bar is always on.
If i try to hide the statusbar in the code below, it works, but then is always off, something i dont want. Only wanna hide it for the fullscreen view.
I actually used this Introspect package from Github to hide the tabbar when the child view is loaded full screen, and i made it work!
SwiftUI hide TabBar in subview
https://github.com/siteline/SwiftUI-Introspect
Actually, I wonder if anyone has used Introspect to hide the statusbar like the tabbar. I tried to use it, but I am a rockie, I only know a bit of SwiftUI, no Swift, no view controller experience, nothing.
But I have a totally functional app with only this issue, and I am super frustrated not to have the skills to know why the tabbar view is forcing a persistent status bar.
Any help, please?
var body: some View {
ZStack {
Color("background2")
.edgesIgnoringSafeArea(.all)
TabView {
RecipeList().tabItem {
Image(systemName: "book.fill")
.font(.system(size: 24, weight: .bold))
Text("Galería")
}
PostList(section: sectionData[0]).tabItem {
Image(systemName: "list.bullet")
.font(.system(size: 22, weight: .bold))
Text("Listado")
}
}
.accentColor(Color("accent"))
.introspectTabBarController { tabBarController in
// customize here the UITabBarViewController if you like
self.viewModel.tabBarController = tabBarController
}
}
}
I can suggest you using the #EnvironmentObject wrapper which basically allows you to use an object as global state. You can find fair amount of tutorials explaining how to do that and inject it in your initial view so that this object is accessible in the whole view hierarchy.
Once you have that global state set up, you can hide your status bar conditionally like this:
MyOutterWrapper {
Text("Some text")
}
.statusBar(hidden: myGlobalState.statusBarHidden)
If you are using NavigationView note that hiding the status bar works best if you set it up there (also assuming navigation view is your first view that appears).
Now all you got to do is inside your view set the variable to true when entering full screen and set it back to false when exiting. Hope that helps!
EDIT: Forgot to mention that hiding status bar as of June 26, 2020 only works if it's set on the initial view. You cannot change it later and that's the reason we set up this variable in order to go back and change the value dynamically.