Launch new window on iOS app using SwiftUI Lifecycle - ios

The following code on WindowScene does indeed open a new window on macOS when a button is pressed in ContentView that opens an URL:
import SwiftUI
#main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
WindowGroup("Viewer") {
Text("Viewer").padding()
}
.handlesExternalEvents(matching: ["*"])
}
}
However, when the same is applied to iOS, the app does not do anything when the openURL action is called.
The result from my research is that I can use the traditional requestSceneSessionActivation to open window manually. However, this will defeat the purpose of using the SwiftUI app lifecycle.
Any suggestions on a working method, without reverting back to the UIKit lifecycle?

After a very long research session, I finally found the property that does this in this blog post.
Turns out that requestSceneSessionActivation is necessary, but there's no need to use a SceneDelegate.
When creating the new session, set the targetContentIdentifier on the NSUserActivity object.
let activity = NSUserActivity(activityType: "newWindow")
activity.userInfo = ["some key":"some value"]
activity.targetContentIdentifier = "newWindow" // IMPORTANT
UIApplication.shared.requestSceneSessionActivation(nil, userActivity: activity, options: nil)
Finally, make sure the new WindowGroup can handle the event with the identifier:
WindowGroup(id: "newWindow") {
Text("New Window!").padding()
}
.handlesExternalEvents(matching: ["newWindow"])
This solution retains the SwiftUI Lifecycle, and also works on Catalyst.
Update for iPadOS 16/macOS Ventura:
You can now use the new openWindow environment property:
#Environment(\.openWindow) private var openWindow
...
openWindow(id: "newWindow")
Make sure the id passed to openWindow is the same as the id set in the WindowGroup or Window initializer.

Related

SwiftUI & requestReview() – review popup not displaying

I am building an app with SwiftUI and would like to use requestReview() to display a review request popup. However, the popup is not displaying. From what I understand from the documentation, when the app is in development mode, the popup should display every time.
I've tested the app in the Xcode simulator and on a real device, I'm using Xcode 14.1. and the app builds without issue. (I'm also a SwiftUI newbie, I think I must be missing something obvious).
import SwiftUI
import StoreKit
struct DetailView: View {
#Environment(\.requestReview) var requestReview
#AppStorage("AppUsedCount") private var appUsedCount: Int = 0
var body: some View {
VStack {...}.onAppear{
let updatedAppUsedCount: Int = appUsedCount + 1
UserDefaults.standard.set(updatedAppUsedCount, forKey: "AppUsedCount")
if (appUsedCount > 5){
requestReview()
}
}
}
}
I also tested without the IF statement, but still no popup. appUsedCount updates as expected.
Thanks in advance!

onOpenURL not called on iOS 15 simulator (SwiftUI)

I have a widget that opens my app via a custom url scheme (myapp:some-deep-link). In my app I have a handler setup like so:
var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL(perform: { url in
//my code
}
}
}
In iOS 14 this works perfectly, in iOS 15 (Simulator) onOpenURL is not called at all. The app launches, but there is no call. I am wondering if this might be a simulator problem or a bug or something I am doing wrong. Any ideas?

Ipad iOS 14: icon badge flickering

I've found this strange behavior on ipad running ipados 14 (I've in both simulator and physical device installed 14.5, with 14.5.1 in the real one).
I need to show an icon badge with a number based on work made within the app, so there is no external push notification service involved in this.
I've set up a ViewModel that keep track of the number to show in the notification badge:
import Combine
import Foundation
class CounterViewModel: ObservableObject {
#Published private(set) var notificationCount = 42
func up() {
self.notificationCount += 1
}
func down() {
self.notificationCount -= 1
}
}
To publish this number on the notification badge on the app icon I'm using the .onAppear method of the contentView
struct ContentView: View {
#EnvironmentObject var counterViewModel: CounterViewModel
#State private var counterCancellable: AnyCancellable?
var body: some View {
Text("Hello World!")
.onAppear {
UNUserNotificationCenter.current().requestAuthorization(options: .badge) { _, error in
if error == nil {
self.counterCancellable = self.counterViewModel.$notificationCount.sink { count in
DispatchQueue.main.async {
UIApplication.shared.applicationIconBadgeNumber = count
}
}
}
}
}
}
}
Finally, the EnvironmentObject is set up on the app
struct IBreviaryApp: App {
#ObservedObject private var counterViewModel = CounterViewModel()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(self.counterViewModel)
}
}
}
so I can share on all the view involved in this count mechanism.
The problem: on the first run of the app, and only on the first one, after accepting the alert about authorising the notifications, when the app is put on background the badge within the icon is shown, but suddenly disappear. In the dock does not even show.
If I click the app (both on dock or on the "desktop") the badge appear in the animation that open the app.
If I scroll between the pages of installed applications and return to the one where my app is installed, the badge now is fixed. If I open another app, so the dock show this new app in the recent used app list, the badge appear here also (and stays this time).
Restarting the ipad or reinstalling the app fixes the problem, but itself remain for the first time you run the app.
EDIT: repo here: https://github.com/artecoop/badgebug
To actually make the problem arise, I needed to change the count number from another function.
EDIT 2:
Here's a video: https://youtu.be/tPWYRm5xFXI
As you may already see on the repo, to mimic another interaction, I've added a 5 second delay and then set 42 in the counter.

Force focus (and restore if minimized) iOS App on macOS

So far I have successfully adapted my app to run on macOS. But there is one thing missing, I want to force-focus my application when a certain notification is triggered.
I have tried using the UiWindow property windowLevel and the method makeKeyAndVisible but they didn‘t do anything.
Does somebody know what else I could try to get my app focused and restored (if it got minimized) ?
It seems like UIWindow.makeKeyAndVisible is ignored in catalyst, but activating the UISceneSession that contains the window does what you're after.
if let session = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first {
UIApplication.shared.requestSceneSessionActivation(session, userActivity: nil, options: nil, errorHandler: nil)
}
Note that calling requestSceneSessionActivation with nil as the first argument will just open a new window.

SwiftUI application lifecycle

In my first SwiftUI app, I have Remote Notifications and Background Processes enabled.
I did add an AppDelegate class, to support notification.
The notifications set the app badge to an appropriate value.
Since this app has these background modes enabled, several lifecycle events are not working:
applicationDidBecomeActive
applicationWillResignActive
applicationDidEnterBackground
applicationWillEnterForeground
Question: where/how do I reset the badge?
Here is how you can observe didBecomeActiveNotification:
#main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
UIApplication.shared.applicationIconBadgeNumber = 0
}
}
}
}
You can observe other notifications in the same way.
Alternatively you can use an #EnvironmentObject to track the application state:
How can I use a method without any page transition or any reboot app

Resources