SwiftUI toggle State bool onTapGesture using main tread - swiftui

I wrote the following to attempt to display a "arrow.down.circle.fill" and then when tapped display a progress view until tasks are done on the main tread. I then want to display the down arrow image again. I noticed it works fine when using a background thread, but then my UI in my main view doesn't update because published changes on background threads aren't allowed.
struct TestAnimation: View {
#State var isLoading: Bool = false
var body: some View {
if !isLoading {
Image(systemName: "arrow.down.circle.fill")
.font(.system(size: 35))
.padding()
.foregroundColor(.blue)
.imageScale(.large)
.onTapGesture {
DoSomthingMainTread()
}
}
else {
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .blue))
.padding(30)
.scaleEffect(3)
}
}
func DoSomthingMainTread(){
DispatchQueue.global(qos: .background).async {
isLoading = true
DispatchQueue.main.async {
sleep(3) //call function here
}
isLoading = false
}
}
}
Thanks for any help!!

You are doing things on the wrong queues.
DispatchQueue.global(qos: .background).async {
isLoading = true // NO!!!! This needs to be on the main queue.
DispatchQueue.main.async {
sleep(3) // NO!!! This should be off the main queue.
}
isLoading = false // NO!!! This needs to be on the main queue.
}
You must update isLoading on the main queue, because it is a property of a View. And you should not perform slow, blocking work (like sleep(3)) on the main queue, because it prevents the user interface from responding to user actions.
Your DoSomthingMainTread method should look like this:
func DoSomthingMainTread(){
// Already on main queue because onTapGesture's body runs on main queue.
isLoading = true
DispatchQueue.global(qos: .background).async {
// On background queue, so OK to perform slow, blocking work.
sleep(3) //call function here
DispatchQueue.main.async {
// Back on main queue, so OK to update isLoading.
isLoading = false
}
}
}

Well, this problem is often encountered in my daily development and I prefer to use .redacted first, but here I will provide a method base on your method.
First of all, in the view body it's better to use ZStack, so the view will be changed into following code:
var body: some View {
ZStack {
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .blue))
.padding(30)
.scaleEffect(3)
.opacity(isLoading ? 1: 0)
Image(systemName: "arrow.down.circle.fill")
.font(.system(size: 35))
.padding()
.foregroundColor(.blue)
.imageScale(.large)
.onTapGesture {
DoSomthingMainTread()
}
.opacity(isLoading ? 0: 1)
}
}
Notice here I use .opacity to decide whether to show the Image or not. And in the DoSomthingMainTread() method, change the code to:
func DoSomthingMainTread(){
isLoading = true
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
isLoading = false
}
}
That's my answer, hope it's useful for you.

As mentioned by others never sleep on the main thread
unless… you use Swift Concurrency, a Task sleeps without blocking the thread
Task { #MainActor in
isLoading = true
try? await Task.sleep(nanoseconds: 3_000_000)
isLoading = false
}
Or if you want to do something in the background and update the loading state on the main thread create an extra function dispatched to the #MainActor
#MainActor func updateLoadingState(_ flag : Bool) {
isLoading = flag
}
and use a detached Task for the background work
Task.detached(priority: .background) {
await updateLoadingState(true)
doSomethingInBackground()
await updateLoadingState(false)
}

Related

LazyVStack in ScrollView has jittery auto scroll

I have a chat app, where whenever a chat room is opened, I need the view to scroll to the bottom as soon as the messages are fetched.
The thing is that although it does scroll perfectly when a new message is received or sent (see ViewModel down below), it is very jittery when I tell it to scroll right after the first batch of messages is fetched, which happens once as soon as the view appears.
After a lot of trial and error, I realized that if I add a small delay to the scroll, it'll improve but not completely! It is like it's trying to scroll to the very bottom, but it'll fail just for a few inches. I also realized that if I add a bigger delay, like 2 seconds, it'll scroll just fine.
Here's the messages list view:
struct MessagesView: View {
#StateObject private var viewModel = ViewModel()
// -----------------------
let currentChatRoom: ChatRoom
// -----------------------
var body: some View {
ZStack {
Color.black.ignoresSafeArea()
VStack {
ScrollView {
ScrollViewReader { proxy in
LazyVStack {
ForEach(viewModel.messages) { message in
MessageView(message: message)
.id(message.id)
.onTapGesture {
viewModel.shouldDismissKeyboard = true
}
}
}
.onChange(of: viewModel.shouldScrollToMessageId) { messageId in
if let messageId = messageId, !messageId.isEmpty {
proxy.scrollTo(messageId, anchor: .bottom)
}
}
}
}
VStack(alignment: .leading) {
if chatEnvironment.isOtherUserTyping {
TypingIndicationView()
}
BottomView()
.padding(.bottom, 4)
}
}
}
.onAppear {
viewModel.setUp(currentChatRoom: currentChatRoom)
}
}
}
As you can see, it’s viewModel.shouldScrollToMessageId that’s responsible for "auto-scrolling" to the last message.
Here’s MessageView:
fileprivate struct MessageView: View {
let message: Message
var body: some View {
HStack {
VStack(alignment: .leading, spacing: 1) {
Text(message.user.isCurrentUser == true ? "You" : "\(message.user.username)")
.foregroundColor(message.user.isCurrentUser == true ? .customGreen : .customBlue)
.multilineTextAlignment(.leading)
.font(.default(size: 16))
.padding(.bottom, 1)
if let imageURL = message.postSource?.imageURL, !imageURL.isEmpty {
VStack(alignment: .leading) {
WebImage(url: .init(string: imageURL))
.resizable()
.indicator(.activity)
.scaledToFill()
.frame(width: UIScreen.main.bounds.width / 2, height: UIScreen.main.bounds.width / 1.45)
.cornerRadius(25)
}
}
Text(message.text)
.foregroundColor(.white)
.multilineTextAlignment(.leading)
.font(.default(size: 16))
}
Spacer()
}
.padding(.bottom, 8)
.padding(.horizontal)
.background(
Color.black
)
}
}
Here’s the ViewModel:
class ViewModel: ObservableObject {
#Published var messages = [Message]()
#Published var text = ""
#Published var shouldScrollToMessageId: String?
#Published var currentChatRoom: ChatRoom?
// -----------------------------
private var isInitialized = false
// -----------------------------
func setUp(currentChatRoom: ChatRoom) {
guard !isInitialized else { return }
isInitialized.toggle()
// -----------------------------
self.currentChatRoom = currentChatRoom
// -----------------------------
getFirstBatchOfMessages(chatRoom: chatRoom)
subscribeToNewMessages()
}
private func getFirstBatchOfMessages(chatRoom: ChatRoom) {
messagesService.getMessages(chatRoomId: chatRoom.id) { [weak self] messages in
DispatchQueue.main.async {
self?.messages = messages
}
self?.scrollToBottom(delay: 0.15)
}
}
private func subscribeToNewMessages() {
...
if !newMessages.isEmpty {
self?.scrollToBottom(delay: 0)
}
}
func scrollToBottom(delay: TimeInterval) {
DispatchQueue.main.async {
self.shouldScrollToMessageId = self.messages.last?.id
}
}
func sendMessage() {
...
scrollToBottom(delay: 0)
}
}
Here, scrollToBottom is responsible for notifying the MessagesView that shouldScrollToMessageId's value changed and that it should scroll to the last message.
Any help will be much appreciated!!!
I am also writing an application with a chat on SwiftUI and I also have a lot of headaches with a bunch of ScrollView and LazyVStack.
In my case, I load messages from the CoreData and display them in a LazyVStack, so in my case, scrolling to the last message does not work, it seems to me simply because a bottom last view did not render, because rendering starts from the top.
Therefore, I came up with a solution with placing an invisible view at the bottom and assigned it a static ID, in my case -1:
VStack(spacing: 0) {
LazyVStack(spacing: 0) {
ForEach(messages) { message in
MessageRowView(viewWidth: wholeViewProxy.size.width, message: message)
.equatable()
}
}
Color.clear.id(-1)
.padding(.bottom, inputViewHeight)
}
I call scroll to this view:
.onAppear {
scrollTo(messageID: -1, animation: nil, scrollReader: scrollReader)
}
And it works... but sometimes...
Sometimes it works correctly, sometimes it stops without scrolling a couple of screens to the end. Looks like LazyVStack is rendering the next views after the scrollTo has finished its work. Also, if add scrolling with some delay it may works better, but not always perfect.
I hope this can be a little helpful and if you find a stable solution I will be very happy if you share :)

How to execute one function after completion of another

I have been trying to execute getData() after the completion of login(), but that never seems to work when using DispatchQueue.main.async
I have only been able to get it to work by forcing a delay, what's the best way to go about this?
Thanks
class DataTask {
func login{...}
func getData{...}
}
struct ContentView: View {
#State private var data = DataTask()
var body: some View{
Text("Hello world")
.onAppear{
data.login()
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0){
func refreshData(){
data.getData()
// update the response into core data
}
}
}
}
}
Never use hard-coded delays to work around an asynchronous task, that's a horrible practice.
To execute a function after the completion of another add a completion handler
class DataTask {
func login(completion: #escaping: () -> Void) {... completion() ...}
func getData {...}
}
...
data.login {
data.getData()
}

How to disable / modify a button using SwiftUI?

I want to create a POC using SwiftUI and CoreML. I use a simple button to call some function (called test here). This function is pretty heavy as it performs a CoreML inference, and it can take up to a minute to compute.
I have several problems:
The button is still active even when the computation is ongoing. In other words, if I click the button several times before the processing of the first click is finished, the processing will be performed several times. I want to disable the button as long as the processing is ongoing.
I tried to modify the button's appearance to signify the user that the processing is ongoing. In the example bellow, I change the button color to red before calling the test function, and I change it back to blue when the processing is over. But it doesn't work.
In the code bellow, the test function is just sleeping for 5 seconds to simulate the CoreML inference.
func test() -> Void {
print("Start processing")
sleep(5)
print("End processing")
}
struct ContentView: View {
#State private var buttonColor : Color = .blue
var body: some View {
VStack {
Button(action: {
self.buttonColor = .red
test()
self.buttonColor = .blue
}) {
Text("Start")
.font(.title)
.padding(.horizontal, 40)
.padding(.vertical, 5)
.background(self.buttonColor)
.foregroundColor(.white)
}
}
}
}
I guess this problem is very straight forward for most of you. I just can't find the correct search keywords to solve it by myself. Thanks for your help.
Here is possible approach (see also comments in code). Tested & works with Xcode 11.2 / iOS 13.2.
struct ContentView: View {
#State private var buttonColor : Color = .blue
var body: some View {
VStack {
Button(action: {
self.buttonColor = .red
DispatchQueue.global(qos: .background).async { // do in background
test()
DispatchQueue.main.async {
self.buttonColor = .blue // work with UI only in main
}
}
}) {
Text("Start")
.font(.title)
.padding(.horizontal, 40)
.padding(.vertical, 5)
.background(self.buttonColor)
.foregroundColor(.white)
}
.disabled(self.buttonColor == .red) // disabled while calculating
}
}
}

Multiple Alerts in one view can only the last alert works always in swiftui

I have two alert which is called if the boolean is true.
Alert - 1 - It is called if there is any issues with the bluetooth state other than powered on.This is called directly from a swift package named BLE. The code snippet is below.
Alert - 2 - It is called when you want to unpair the peripheral giving the user two options.Unpair or remain on the same page.
Issue :
Both the alert seems to be working fine but if they are not placed in the same view. When I place the alert in the same view the last displayed alert is called from the sequence top to bottom.
The OS reads the first alert but only activates the second alert if it's called.
Is there a way to make both alert functional if they are called.
I referred to below solution but i was getting the same results.
Solution 1 and Solution 2
There are 2 Code snippets
1. Main Application
import SwiftUI
import BLE
struct Dashboard: View {
#EnvironmentObject var BLE: BLE
#State private var showUnpairAlert: Bool = false
private var topLayer: HeatPeripheral {
self.BLE.peripherals.baseLayer.top
}
var body: some View {
VStack(alignment: .center, spacing: 0) {
// MARK: - Menu Bar
VStack(alignment: .center, spacing: 4) {
Button(action: {
print("Unpair tapped!")
self.showUnpairAlert = true
}) {
HStack {
Text("Unpair")
.fontWeight(.bold)
.font(.body)
}
.frame(minWidth: 85, minHeight: 35)
.cornerRadius(30)
}
}
}
.onAppear(perform: {
self.BLE.update()
})
// Alert 1 - It is called if it meets one of the cases and returns the alert
// It is presented in the function centralManagerDidUpdateState
.alert(isPresented: $BLE.showStateAlert, content: { () -> Alert in
let state = self.BLE.centralManager!.state
var message = ""
switch state {
case .unknown:
message = "Bluetooth state is unknown"
case .resetting:
message = "Bluetooth is resetting..."
case .unsupported:
message = "This device doesn't have a bluetooth radio."
case .unauthorized:
message = "Turn On Bluetooth In The Settings App to Allow Battery to Connect to App."
case .poweredOff:
message = "Turn On Bluetooth to Allow Battery to Connect to App."
break
#unknown default:
break
}
return Alert(title: Text("Bluetooth is \(self.BLE.getStateString())"), message: Text(message), dismissButton: .default(Text("OK")))
})
// Alert 2 - It is called when you tap the unpair button
.alert(isPresented: $showUnpairAlert) {
Alert(title: Text("Unpair from \(checkForDeviceInformation())"), message: Text("*Your peripheral command will stay on."), primaryButton: .destructive(Text("Unpair")) {
self.unpairAndSetDefaultDeviceInformation()
}, secondaryButton: .cancel())
}
}
func unpairAndSetDefaultDeviceInformation() {
defaults.set(defaultDeviceinformation, forKey: Keys.deviceInformation)
disconnectPeripheral()
print("Pod unpaired and view changed to Onboarding")
self.presentationMode.wrappedValue.dismiss()
DispatchQueue.main.async {
self.activateLink = true
}
}
func disconnectPeripheral(){
if skiinBLE.peripherals.baseLayer.top.cbPeripheral != nil {
self.skiinBLE.disconnectPeripheral()
}
}
}
2. BLE Package
import SwiftUI
import Combine
import CoreBluetooth
public class BLE: NSObject, ObservableObject {
public var centralManager: CBCentralManager? = nil
public let baseLayerServices = "XXXXXXXXXXXXXXX"
let defaults = UserDefaults.standard
#Published public var showStateAlert: Bool = false
public func start() {
self.centralManager = CBCentralManager(delegate: self, queue: nil, options: nil)
self.centralManager?.delegate = self
}
public func getStateString() -> String {
guard let state = self.centralManager?.state else { return String() }
switch state {
case .unknown:
return "Unknown"
case .resetting:
return "Resetting"
case .unsupported:
return "Unsupported"
case .unauthorized:
return "Unauthorized"
case .poweredOff:
return "Powered Off"
case .poweredOn:
return "Powered On"
#unknown default:
return String()
}
}
}
extension BLE: CBCentralManagerDelegate {
public func centralManagerDidUpdateState(_ central: CBCentralManager) {
print("state: \(self.getStateString())")
if central.state == .poweredOn {
self.showStateAlert = false
if let connectedPeripherals = self.centralManager?.retrieveConnectedPeripherals(withServices: self.baseLayerServices), connectedPeripherals.count > 0 {
print("Already connected: \(connectedPeripherals.map{$0.name}), self.peripherals: \(self.peripherals)")
self.centralManager?.stopScan()
}
else {
print("scanForPeripherals")
self.centralManager?.scanForPeripherals(withServices: self.baseLayerServices, options: nil)
}
}
else {
self.showStateAlert = true // Alert is called if there is any issue with the state.
}
}
}
Thank You !!!
The thing to remember is that view modifiers don't really just modify a view, they return a whole new view. So the first alert modifier returns a new view that handles alerts in the first way. The second alert modifier returns a new view that modifies alerts the second way (overwriting the first method) and that's the only one that ultimately is in effect. The outermost modifier is what matters.
There are couple things you can try, first try attaching the different alert modifiers to two different view, not the same one.
Second you can try the alternate form of alert that takes a Binding of an optional Identifiable and passes that on to the closure. When value is nil, nothing happens. When the state of changes to something other than nil, the alert should appear.
Here's an example using the alert(item:) form as opposed to the Bool based alert(isPresented:).
enum Selection: Int, Identifiable {
case a, b, c
var id: Int { rawValue }
}
struct MultiAlertView: View {
#State private var selection: Selection? = nil
var body: some View {
HStack {
Button(action: {
self.selection = .a
}) { Text("a") }
Button(action: {
self.selection = .b
}) { Text("b") }
}.alert(item: $selection) { (s: Selection) -> Alert in
Alert(title: Text("selection: \(s.rawValue)"))
}
}
}

How to create a SwiftUI button that changes opacity and triggers button action when touched?

I wanna create a button with SwiftUI that fires the moment my finger touches it (like UIKit's touch down instead of touch up inside). I also want the opacity of the button to become 0.7 when my finger is pressing the button. And I want the opacity of the button to change back to 1 ONLY when my finger is no longer touching the button.
I've tried 2 different types of button styles to create such a button but both of them failed:
struct ContentView: View {
var body: some View {
Button(action: {
print("action triggered")
}){
Text("Button").padding()
}
.buttonStyle(SomeButtonStyle())
}
}
struct SomeButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.background(Color.green)
.opacity(configuration.isPressed ? 0.7 : 1)
.onLongPressGesture(
minimumDuration: 0,
perform: configuration.trigger//Value of type 'SomeButtonStyle.Configuration' (aka 'ButtonStyleConfiguration') has no member 'trigger'
)
}
}
struct SomePrimativeButtonStyle: PrimitiveButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.background(Color.green)
.opacity(configuration.isPressed ? 0.7 : 1)//Value of type 'SomePrimativeButtonStyle.Configuration' (aka 'PrimitiveButtonStyleConfiguration') has no member 'isPressed'
.onLongPressGesture(
minimumDuration: 0,
perform: configuration.trigger
)
}
}
Apparently none of the button styles above worked because ButtonStyle and PrimitiveButtonStyle don't share the same methods and properties so I can't use both the isPressed property (which belongs to ButtonStyle) AND the trigger method (which belongs to PrimitiveButtonStyle) in the same button style.
How should I configure my button style to make this work?
Ok, I understand that author wants to see solution only with Button, so I dig a little more. And found something interesting at Swift UI Lab. The idea is the same as in my first answer: use #GestureState and create LongPressGesture which .updating($...) this state. But in PrimitiveButtonStyle you don't need to compose a few gestures together. So, I simplified code a little and tested it at simulator. And I think now it just what author need:
struct ComposingGestures: View {
var body: some View {
Button(action: {
print("action triggered")
}){
Text("Button")
.padding()
}
.buttonStyle(MyPrimitiveButtonStyle())
}
}
struct MyPrimitiveButtonStyle: PrimitiveButtonStyle {
func makeBody(configuration: PrimitiveButtonStyle.Configuration) -> some View {
MyButton(configuration: configuration)
}
struct MyButton: View {
#GestureState private var pressed = false
let configuration: PrimitiveButtonStyle.Configuration
let color: Color = .green
#State private var didTriggered = false
var body: some View {
// you can set minimumDuration to Double.greatestFiniteMagnitude if you think that
// user can hold button for such a long time
let longPress = LongPressGesture(minimumDuration: 300, maximumDistance: 300.0)
.updating($pressed) { value, state, _ in
state = value
self.configuration.trigger()
}
return configuration.label
.background(Color.green)
.opacity(pressed ? 0.5 : 1.0)
.gesture(longPress)
}
}
}
I didn't work with ButtonStyle, but tried to solve it with Composing SwiftUI Gestures. I compose TapGesture and LongPressGesture and playing with #GestureState to control .opacity of "button" (which is just Text). The result is just as you asked:
struct ComposingGestures: View {
enum TapAndLongPress {
case inactive
case pressing
var isPressing: Bool {
return self == .pressing
}
}
#GestureState var gestureState = TapAndLongPress.inactive
#State private var didPress = false
var body: some View {
let tapAndLongPressGesture = LongPressGesture(minimumDuration: 2) // if minimumDuration <= 1 gesture state returns to inactive in 1 second
.sequenced(before: TapGesture())
.updating($gestureState) { value, state, transaction in
switch value {
case .first(true), .second(true, nil):
self.didPress = true // simulation of firing action
state = .pressing
default:
state = .pressing
}
}
return VStack {
Text("action was fired!")
.opacity(didPress ? 1 : 0)
Text("Hello world!")
.gesture(tapAndLongPressGesture)
.background(Color.green)
.opacity(gestureState.isPressing ? 0.7 : 1)
}
}
}
P.S. I played only with #State var didPress to show, how to fire action. Maybe it's better to fire it only in the first case, like this:
// ...
.updating($gestureState) { value, state, transaction in
switch value {
case .first(true):
self.didPress = true // simulation of firing action
state = .pressing
case .second(true, nil):
state = .pressing
default:
state = .pressing
}
UPDATE
tried code at simulator and fixed two mistakes:
// ...
let tapAndLongPressGesture = LongPressGesture(minimumDuration: 300, maximumDistance: 300) // now button don't return opacity to 1 even if you move your finger
// ...
case .first(true), .second(true, nil):
DispatchQueue.main.async { // now there are no purple mistakes
self.didPress = true // simulation of firing action
}
state = .pressing
// ...