Post

Replies

Boosts

Views

Activity

Request Notification Service Entitlement to filter remote notifications IOS
I have a sample app to test push notifications. The app has a Notification Service Extension to intercept remote notifications, update/enhance the content and then display it to user. But there are some scenarios where the app shouldn't end up displaying a notification to user... Like, due to slow internet, the time taken to download media content (like images) exceeds the 30 sec time limit. There are more app specific scenarios. Basically, every push received from APNS need not be shown to user. Notification Service Extension did not have this power to suppress remote notifications. In the end, it will always display a notification to user. From iOS 13.3 onwards, Notification Service Extension has the ability to filter out these remote notifications. The first step is (quoting form the documentation), This entitlement allows a notification service extension to receive remote notifications without displaying the notification to the user. To apply for this entitlement, see Request Notification Service Entitlement. When I click on the hyperlink (you need to be an account holder to view that page), Apple asks for some info like 'App Store URL', 'When extension runs, what system and network resources does it need?' and so on. I only have a sample app to help understand the aspects of notifications. I don't have any full-fledged app in AppStore... yet... and I have no clue what all my full-fledged app will be doing in the extension (since I'm just in learning stage). I only have a sample app, where I log and perform some basic string operations when my extension is invoked. Due to this, I'm unable to see the extension filtering out notifications. How does anyone test this feature? Has anyone tried it? Really appreciate any guidance. I'm not sure how to proceed..
0
0
1.6k
May ’23
'Import-path' in Import declaration's documentation
According to swift documentation, the following describes the various forms of the Import declaration. Grammar of an import declaration import-declaration → attributes? import import-kind? import-path import-kind → typealias | struct | class | enum | protocol | let | var | func import-path → identifier | identifier . import-path Questions: Attributes and import-kind are optional. import-kind refers to the type of the import (class, struct, enum etc etc).... defined in the second line. Does attributes refers to @available which can used to add an import for a specific platform version? In the 3rd line, I understand that identifier here refers to the names of modules, classes, funcs etc., but what does import-path mean? Can I give the actual path in disk? What all comes under this? I couldn't understand from this documentation.
0
0
631
Aug ’23
No response from AppleDTS
I've reached out to AppleDTS for code-level support on Dec 19th 2023. It's been 3 weeks now (Jan 11, 2024). I sent a follow-up 3 days ago, but no response yet. Their response time is supposed to be within 3 business days.. experiencing this level of delay in a paid support is disappointing. I'm not raising a new TSI but resuming an old one after almost 8 months because it is a continuation of the same problem. Delayed response from my side is a problem? I hope not (I didn't find any restrictions in the documentation). What should I do in this situation?
0
0
637
Jan ’24
WatchOS app launched by tapping an associated file
In iPhone, if you open Files app and tap on an associated file type, its corresponding app is launched. I have implemented this functionality in my iOS SwiftUI app - associated a file type - .csk, with my iOS app and handled its launch using the onOpenURL(perform:) modifier. WindowGroup { FileContentView() .onOpenURL(perform: { (fileUrl: URL) in Log(String(format: "File Url = %@", fileUrl.absoluteString)) // Update UI with the content of the file }) } I want to achieve the same for my watchOS app. I noticed that the UTExportedTypesDeclaration key, which is used to declare the file types created and owned by the app, is not available for watchOS. But the CFBundleDocumentTypes key, which is used to associate a file type with the app is available. So, I expect my app to respond to taps on those associated file types, but I've run into a snag. There is no Files app in AppleWatch nor is there a way to view my iCloud storage. I have my .csk file (which is associated with the watchOS app) in iCloud. So, how can I test this launch? How can an AppleWatch user tap a file and view it in his app? It should be possible to handle file launches since CFBundleDocumentTypes is available for watchOS.
0
0
631
Mar ’24
IOS SceneDelegate not invoked when extended in a different target
I have an iOS project with the following targets: SwiftExtensions (AppTarget) -> depends on Experience Experience (StaticLibrary) -> depends on Lifecycle Lifecycle (StaticLibrary) I have defined the SceneDelegate in Lifecycle library: public class SceneDelegate: UIResponder, UIWindowSceneDelegate { // scene(_:willConnectTo:options:) is implemented in Experience // scene(_:openURLContexts:) is implemented in Experience // Other methods such as sceneWillEnterForeground(_:), sceneDidBecomeActive(_:) etc. } As shown above, scene(_:willConnectTo:options:) and scene(_:openURLContexts:) are not defined here. In the Experience library, SceneDelegate is extended: extension SceneDelegate { func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { NSLog("[Experience]: SceneDelegate.scene(_:willConnectTo:options:)") if (connectionOptions.urlContexts.isEmpty) { NSLog("[Experience]: Not launched using file!") } else { NSLog("[Experience]: Launched using file!") let urlContexts: Set<UIOpenURLContext> = connectionOptions.urlContexts for (index, urlContext) in urlContexts.enumerated() { NSLog(String(format: "[Experience]: url[%d] = %@ ", index, urlContext.url.path())) } } } func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { NSLog("[Experience]: SceneDelegate.scene(_:openURLContexts:)") for (index, urlContext) in URLContexts.enumerated() { NSLog(String(format: "[Experience]: url[%d] = %@ ", index, urlContext.url.path())) } } } Now, when I tap the app icon, scene(_:willConnectTo:options:) is not invoked. When I tap an associated file type, scene(_:willConnectTo:options:) is not invoked, again. If app is running in background, and I foreground the app by tapping an associated file type, scene(_:openURLContexts:) is not invoked. Basically, when I define these two methods outside the target, despite with public access modifier, iOS doesn't invoke my delegate methods defined in the other library. My understanding was, Extensions can be used to break up the class. What is missing here?
0
0
833
Mar ’24
Deep links in AppleWatch
This page describes the procedure to create deep links in iOS. I was able to launch an IOS Companion app (name of the app in my case) using its deep link. But the same is not working in AppleWatch. This is my plist to register a custom scheme - Companion: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleURLTypes</key> <array> <dict> <!-- <key>CFBundleTypeRole</key> <string>Viewer</string> --> <key>CFBundleURLName</key> <string><some unique ID></string> <key>CFBundleURLSchemes</key> <array> <string>Companion</string> </array> </dict> </array> </dict> </plist> I have implemented onOpenURL(perform:) to handle app launches using a deep link (url). var body: some Scene { WindowGroup { ContentView() .onOpenURL(perform: { (link: URL) in Log(String(format: "Link = %@", link.absoluteString)) // Use then deep link }) } } In iOS, I tested deep links in two ways: Wrote the full deep link in Notes app and tapped it. Created another app called AppLauncher with a Button saying 'Launch using Deep link'.... which when clicked opens the deep link using open(_:options:completionHandler:). Both the approaches work in iOS, but in watchOS, I can only try 2 because Notes app is not available for AppleWatch. So, I created another watchOS app called AppLauncher, which displays a SwiftUI Button saying 'Launch using Deep link', which when tapped, tries to open the link using openSystemURL(_:). But as mentioned in the documentation (linked earlier), Opens the specified system URL. this API only works for links associated with System apps i.e., Apple's call and message apps. So, how else can I use deep link to launch another app? I believe it's possible to launch an app using its deep link because the info.plist keys required to define a deep link scheme association (CFBundleURLTypes, CFBundleURLSchemes etc) is valid for watchOS too.
0
0
1.1k
Mar ’24
Set swift macros from cmake
I have a swift project which uses macros for conditional compilation. How to set macro: Go to Target -> BuildSettings -> Swift Compiler - Custom Flags -> Active Compilation Conditions and add your macro (Ex: sample macro - ELDIABLO in this case). Then the following swift code, #if ELDIABLO NSLog("ELDIABLO macro detected!") #else NSLog("ELDIABLO macro not detected!") #endif ...produces the desired output. ELDIABLO macro detected! Now, how do I achieve this through cmake? When I do the following, set(CMAKE_Swift_FLAGS "${CMAKE_Swift_FLAGS} ELDIABLO") the macro gets added to Swift Compiler - Custom Flags -> Other Swift Flags (shown in the above image besides Active Compilation Conditions). But it must be added in Swift Compiler - Custom Flags -> Active Compilation Conditions, else (here's why), it will not get detected in swift files. How can I set swift macros in Active Compilation Conditions through cmake?
0
0
777
Sep ’22
Exclude notification delegate methods for tvOS using @available
UserNotifications framework helps the app to handle all notification related aspects. The userNotificationCenter(_:didReceive:withCompletionHandler:) delegate method is used to handle user's action (dismiss, selected button, tap, text input etc.). As evident from the documentation, this method is available in iOS and iPadOS but not tvOS. The @available attribute is one way to exclude methods. @available(iOS 10.0, *) func userNotificationCenter (_ pNotificationCenter: UNUserNotificationCenter, didReceive pResponse: UNNotificationResponse, withCompletionHandler pCompletionHandler: @escaping () -> Void) -> Void { // Handle user's action on a notification. ... } When the delegate method is declared as above, I expect it to be included only for iPadOS and iOS. When building for tvOS, I get the following error: error: 'UNNotificationResponse' is unavailable in tvOS error: cannot override 'userNotificationCenter' which has been marked unavailable Clearly, it is included for tvOS also. Another approach is using #if os(iOS) and it does work... I don't get the above errors, meaning the code is not included for tvOS. But I want to understand how to achieve this using @available attribute because I have other situations where I need to exclude methods for certain versions of the same OS. How do I exclude userNotificationCenter(_:didReceive:withCompletionHandler:) for tvOS using @available attribute?
1
0
1k
May ’23
Application lifecycle - AppDelegate method Vs Notification Center
There are two ways to capture application transitioning to foregorund/background and inactive/active. Lets take the event received when app transitions to the inactive state as an example. Implement the corresponding AppDelegate method - applicationWillResignActive(_:) func applicationWillResignActive(_ application: UIApplication) { Log("applciationWillResignActive(_:)") } Register for willResignActiveNotification during startup NotificationCenter.default.addObserver(forName:UIApplication.willResignActiveNotification, object: nil, queue: .main) { (broadcastNotification: Notification) in Log("Received " + String(describing: broadcastNotification.name)) } When I tested in code, both works. First, the applicationWillResignActive(_:) delegate method is invoked and then, willResignActiveNotification is received (as mentioned in the documentation). But I'm unable to decide which to use... even after reading their documentation. What is the recommendation? If both are fine, then there are two different ways to achieve the same thing... there's gotta be some purpose, right?
2
0
1.5k
Aug ’23
IOS Notifications: Embedded binary's bundle identifier is not prefixed with the parent app's bundle identifier
I have an iOS app, which uses Notification Service Extension (NSE) for its functioning. When I build the app, I get the following error: error: Embedded binary's bundle identifier is not prefixed with the parent app's bundle identifier. Embedded Binary Bundle Identifier: (null) Parent App Bundle Identifier: com.example.sample This error occurs when NSE doesn't have the app's bundle identifier prefixed to it (Reference post). In my case, the bundle ID of the app is com.example.sample and the bundle ID of the extension, com.example.sample.NSESample (checked these values in Project -&gt; Target -&gt; Signing &amp; capabilities -&gt; bundle identifier label). I believe this is as expected. I don't understand this error now, which says the embedded bundle identifier is null. I cleaned and built the app again..... same error. According to this stackoverflow post, you have to enable 'Copy only when installing'. When I tried, it worked. I don't know what this setting means and how this solves the issue. I'm unable to find any documentation reg this setting. Idk if this is even a valid solution, because the error says 'Embedded Binary Bundle Identifier' is null. Why is the embedded bundle identifier null (despite the Xcode interface showing a valid bundle ID)? How can I solve this?
0
0
1.9k
Feb ’24
64-bit Apple Watches with 64-bit pointer sizes?
I have a watchOS app written in C++, Swift and SwiftUI. This app is meant only for 64-bit architecture. I know Apple uses the arm architecture, so I thought arm64 will be the arch of latest AppleWatches. I tested my code in x64 simulator (Intel Mac) and arm64 simulator (silicon Mac) - no trouble. Next is to test on a device - AppleWatch Series 9, model: A2984. I set the arch to arm64 and my application failed to build, with Xcode showing a popup about arch mismatch... which is due to the app's arch begin different from device's arch. When I change Xcode arch setting to arm64_32, then I don't get this popup, but my builds fail. When I read about arm64_32, I realised that this is a version of arm64 with 32 bit pointers... not the arm64 with 64 bit pointers. Looking at the specification of AppleWatch Series 9, Apple has confirmed that it has 64 bit CPU, but the instruction set is unknown. This wiki page about different AppleWatch CPUs is marked TBC for AppleWatch Series 9. From Xcode, I got to know that this unconfirmed arch is arm64_32. This completely breaks my code. Are there any 64-bit watches with 64-bit pointer sizes? What is Apple's future in this area? Do they plan to release AppleWatches that support 64-bit pointers or it's always going to be 32?
1
0
1.3k
Jul ’24
Swift Exception Handling in Apple OSes
I have an app whose logic is in C++ and rest of the parts (UI) are in Swift and SwiftUI. Exceptions can occur in C++ and Swift. I've got the C++ part covered by using the Linux's signal handler mechanism to trap signals which get raised due to exceptions. But how should I capture exceptions in Swift? When I say exceptions in Swift, I mean, divide by zero, force unwrapping of an optional containing nil, out of index access in an array, etc. Basically, anything that can go wrong, I don't want my app to abruptly crash... I need a chance to finalise my stuff, alert the user, prepare diagnostic reports and terminate. I'm looking for a 'catch-all' exception handler. As an example, let's take Android. In Android, there is the setDefaultUncaughtExceptionHandler method to register for all kinds of exceptions in any thread in Kotlin. I'm looking for something similar in Swift that should work for macOS, iOS &amp; iPadOS, tvOS and watchOS. I first came across the NSSetUncaughtExceptionHandler method. My understanding is, this only works when I explicitly raise NSExceptions. When I tested it, observed that the exception handler didn't get invoked for either case - divide by zero or invoking raise. class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { Log("AppDelegate.applicationDidFinishLaunching(_:)") // Set the 'catch-all' exception handler for Swift exceptions. Log("Registering exception handler using NSSetUncaughtExceptionHandler()...") NSSetUncaughtExceptionHandler { (exception: NSException) in Log("AppDelegate.NSUncaughtExceptionHandler()") Log("Exception: \(exception)") } Log("Registering exception handler using NSSetUncaughtExceptionHandler() succeeded!") // For C++, use the Linux's signal mechanism. ExceptionHandlingCpp.RegisterSignals() //ExceptionHandlingCpp.TestExceptionHandler() AppDelegate.TestExceptionHandlerSwift() } static func TestExceptionHandlerSwift() { Log("AppDelegate.TestExceptionHandlerSwift()") DivisionByZero(0) } private static func DivisionByZero(_ divisor: Int) { Log("AppDelegate.DivisionByZero()") let num1: Int = 2 Log("Raising Exception...") //let result: Int = num1/divisor let exception: NSException = NSException(name: NSExceptionName(rawValue: "arbitrary"), reason: "arbitrary reason", userInfo: nil) exception.raise() Log("Returning from DivisionByZero()") } } In the above code, dividing by zero, nor raising a NSException invokes the closure passed to NSSetUncaughtExceptionHandler, evident from the following output logs AppDelegate.applicationWillFinishLaunching(_:) AppDelegate.applicationDidFinishLaunching(_:) Registering exception handler using NSSetUncaughtExceptionHandler()... Registering exception handler using NSSetUncaughtExceptionHandler() succeeded! ExceptionHandlingCpp::RegisterSignals() .... AppDelegate.TestExceptionHandlerSwift() AppDelegate.DivisionByZero() Raising Exception... Currently, I'm reading about ExceptionHandling framework, but this is valid only for macOS. What is the recommended way to capture runtime issues in Swift?
7
0
1k
Nov ’24
SIGFPE not raised when dividing by zero
I have an app whose logic is in C++ and rest of the parts (UI) are in Swift and SwiftUI. When an exception is raised by some C++ code, I'm using the Linux signal handler mechanism to trap it. From my previous post, I understand that fatal exceptions like SIGSEGV, SIGBUS, SIGFPE etc., there's nothing much that can be done by the process. My only intent for using a signal handler is to log something, so that it becomes easy to fix during development. Ofc, even that logging can fail, based on the severity of the exception, but that's okay... make an attempt to log - if it works, great, else the process can terminate. I'm registering for SIGSEGV and SIGFPE with the following code // ExceptionHandlingCpp.hpp file struct tSignals { SignalHandlerFunc signalHandlerFunc; uint32_t signal; [[maybe_unused]] uint8_t reserved[4]; }; // ExceptionHandlingCpp.cpp file tSignals ExceptionHandlingCpp::unixSignals[] = { {HandleSignals, SIGFPE, {0}}, {HandleSignals, SIGSEGV, {0}}, {HandleSignals, SIGKILL, {0}}, }; std::string ExceptionHandlingCpp::signalToString(int signal) { switch(signal) { case SIGFPE: return "SIGFPE"; case SIGSEGV: return "SIGSEGV"; case SIGKILL: return "SIGKILL"; default: return "Unknown signal"; } } void ExceptionHandlingCpp::RegisterSignals() { LOG("ExceptionHandlingCpp::RegisterSignals()"); struct sigaction sa; sa.sa_flags = SA_SIGINFO; for(int i = 0; i &lt; sizeof(unixSignals)/sizeof(tSignals); ++i) { sa.sa_sigaction = unixSignals[i].signalHandlerFunc; if(sigaction(unixSignals[i].signal, &amp;sa, nullptr) == 1) { LOG("Failed to set " + signalToString(unixSignals[i].signal) + "'s signal handler!"); } else { LOG(signalToString(unixSignals[i].signal) + "'s signal handler set sucessfully!"); } } } In my signal handler (HandleSignals method), immediately after trapping a signal, I log something and set the default handler... This breaks out of the loop that occurs when returning from the signal handler. // ExceptionHandlingCpp.cpp void ExceptionHandlingCpp::HandleSignals(int pSignal, siginfo_t *pInfo, void *pContext) { LOG("ExceptionHandlingCpp::HandleSignals(int, signinfo_t*, void*)"); LOG("signal = " + signalToString(pSignal)); UnregisterSignals(pSignal); LOG("Returning from exception handler..."); } void ExceptionHandlingCpp::UnregisterSignals(int pSignal) { LOG("UnregisterSignals(int)"); struct sigaction defaultAction {}; defaultAction.sa_handler = SIG_DFL; if(sigaction(pSignal, &amp;defaultAction, nullptr) == -1) { LOG("Error in resetting action for " + signalToString(pSignal)); } else { LOG("Successfully reset " + signalToString(pSignal) + "'s action to default!"); } } When I test this code by raising SIGSEGV (as shown below), void ExceptionHandlingCpp::DereferenceNullPtr () { LOG("DereferenceNullPtr()"); int* ptr = nullptr; LOG("Raising exception..."); int value = *ptr; } everything works as expected. Signal handler is invoked, default handler is set and the process immediately quits. But when I try to raise a SIGFPE, void* ExceptionHandlingCpp::DivisionByZero ([[maybe_unused]] void* pParms) { LOG("DivisionByZero()"); int num1; int num2; int result; num1 = 5; num2 = 0; LOG("Raising exception..."); result = num1 / num2; LOG("Returning from DivisionByZero() method"); return nullptr; } my signal handler is not invoked (as shown in the logs below). The process doesn't terminate either. It seems that the flow simply 'walks over' this division by zero instruction as if nothing happened and returns from that method, which shouldn't have happened, as the process should've terminated after reaching my signal handler. RegisterSignals() SIGFPE's signal handler set sucessfully! SIGSEGV's signal handler set sucessfully! SIGKILL's signal handler set sucessfully! .... DivisionByZero() Raising exception... Returning from DivisionByZero() method .... AppDelegate.applicationWillBecomeActive(_:) AppDelegate.applicationDidBecomeActive(_:) ... // UI is displayed Why is SIGFPE not raised? What am I missing here?
4
0
518
Dec ’24
Using handleExternalEvents scene modifier to route external events to the correct scene
In an iPadOS SwiftUI app supporting multiple scenes, each Scene responds to a particular way in which the app was launched. If app was launched by tapping an associated file or a deep link (custom URL), then, the URLHandlerScene is invoked. If app was launched by QuickAction (long tap on the app icon), then another Scene is invoked etc. Each Scene has a purpose and responds to a particular launch. But after defining handlesExternlEvents(matching:) scene modifier, the scene was not getting launched when user taps the associated file or the app's Deeplinks was invoked. @main struct IOSSwiftUIScenesApp: App { var body: some Scene { DefaultScene() URLHandlerScene() .handlesExternalEvents(matching: ["file://"]) // Launched by an associated file .handlesExternalEvents(matching: ["Companion://"]) // Launched by Deeplink. // Other scenes } } struct URLHandlerScene: Scene { @State private var inputURL: URL // Store the incoming URL init() { self.inputURL = URL(string: "Temp://")! } var body: some Scene { WindowGroup { URLhandlerView(inputURL: $inputURL) .onOpenURL(perform: { (fileURL: URL) in log(String(format: "URLhandlerView().onOpenURL | Thread.current = %@", String(describing: Thread.current))) log("fileURL = " + String(describing: fileURL)) inputURL = fileURL }) } } } As shown above, I've attached handlesExternalEvents(matching:) modifier with "file://" for the associate file and "Companion" is my custom URL scheme. As per the scene matching rules documented here, my URLHandlerScene should get launched, but every time I launch the app using associated file or 'open' a Deeplink, the DefaultScene is always launched. What is missing here? Can someone please help?
1
0
128
Apr ’25
Huge timeout values from a failed DiskIO call
I have created a sample app which read/write from a network file. When the file was attempted to open (using open Linux API), connection to network file was lost. The thread which was stuck on the open method, returns after a long time. It was observed that for macOS, the maximum return time of the thread was around 10 mins, whereas in Windows and Linux, the maximum timeout was 60 sec and 90 sec. macOS has a very large timeout before returning the thread with a network failure error. Is this by designed and expected? With a large timeout as 10mins, it's difficult to respond swiftly back to the user.
7
0
243
Sep ’25