Delve into the world of built-in app and system services available to developers. Discuss leveraging these services to enhance your app's functionality and user experience.

Post

Replies

Boosts

Views

Activity

Background Transfer Service and Client Certificates
I can't get NSURLSession background tasks to use client certificates.I have a simple app that creates an NSURLSessionDownloadTask from an NSURLSession that uses NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(...).I have a custom delegate that implements:"func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)". For NSURLAuthenticationMethodServerTrust, I accept any server. For NSURLAuthenticationMethodClientCertificate, I have a hardcoded PKCS12 bundle with a single certificate and key from which I successfully create an NSURLCredential (using SecPKCS12Import), then pass that credential to the completion handler with .UseCredential.At runtime, I get the didReceiveChallenge callback for ClientCertificate, then another for NSURLAuthenticationMethodServerTrust, then URLSessionDidFinishEventsForBackgroundURLSession right away without completing the TLS handshake.If I change the NSURLSessionConfiguration to use NSURLSessionConfiguration.defaultSessionConfiguration(), the client cert is presented correctly and the download proceeds.Both tests are done with the app in the foreground.
17
0
8.2k
Dec ’15
Debugging WidgetKit install error "Failed to get descriptors for extensionBundleID"
I'm trying to create an iOS 14 WidgetKit widget. It's compiling, but when I try to run it, on either simulator or device, I get the error below: Any suggestions on how to debug this? Details SendProcessControlEvent:toPid: encountered an error: Error Domain=com.apple.dt.deviceprocesscontrolservice Code=8 "Failed to show Widget 'com.myapp.dev.WidgetKitExtension' error: Error Domain=SBAvocadoDebuggingControllerErrorDomain Code=1 "Failed to get descriptors for extensionBundleID (com.myapp.dev.WidgetKitExtension)" UserInfo={NSLocalizedDescription=Failed to get descriptors for extensionBundleID (com.myapp.dev.WidgetKitExtension)}." UserInfo={NSLocalizedDescription=Failed to show Widget 'com.myapp.dev.WidgetKitExtension' error: Error Domain=SBAvocadoDebuggingControllerErrorDomain Code=1 "Failed to get descriptors for extensionBundleID (com.myapp.dev.WidgetKitExtension)" UserInfo={NSLocalizedDescription=Failed to get descriptors for extensionBundleID (com.myapp.dev.WidgetKitExtension)}., NSUnderlyingError=0x7fc0b0d12540 {Error Domain=SBAvocadoDebuggingControllerErrorDomain Code=1 "Failed to get descriptors for extensionBundleID (com.myapp.dev.WidgetKitExtension)" UserInfo={NSLocalizedDescription=Failed to get descriptors for extensionBundleID (com.myapp.dev.WidgetKitExtension)}}} Domain: DTXMessage Code: 1- System Information macOS Version 10.15.5 (Build 19F101) Xcode 12.0 (17177)
34
0
22k
Jun ’20
How to "upgrade" an HTTP connection to a WebSocket
Hi, I have been successful at writing Swift code using a NWListener to listen to WebSocket connections on a specific port, but I do not seem to be able to get the path from the URL for creating different types of connections. For instance, differentiating between ws://127.0.0.1:80/updates and ws://127.0.0.1:80/changes. I'd like to be able to get the "updates" or "changes" part when I receive the new connection notification. Having more sample code around WebSockets and how the upgrade process works that would also be great. Thank you ! Daniel Tapie
3
0
3.6k
Sep ’20
Updating Widgets from StaticConfiguration to IntentConfiguration Requires Re-Installation
I'm updating my widget from StaticConfiguration to IntentConfiguration. When I do so, existing widgets installed within simulators and on my iPhone device either show a blank screen or a placeholder screen and fail to initialize. Is there a safe way to upgrade my widget configuration? I would hate to break the widget for our existing users and force them to manually reinstall.
10
0
2.7k
Sep ’20
iOS 14 CoreFoundation crash with EXC_BREAKPOINT
Hi, I am facing a strange issue in my app with iOS14 there is a intermittent crash, i am using NetServiceBrowser for MDNS discovery not sure if that is causing the problem crash log has below information: Crashed: com.apple.main-thread 0 CoreFoundation 0x1a906c4c4 CFAssertMismatchedTypeID + 108 1 CoreFoundation 0x1a8f7db0c CFRunLoopSourceRemoveFromRunLoop + 298 2 CFNetwork 0x1a96255b0 CFNetServiceBrowserStopSearch + 460 3 CoreFoundation 0x1a8f81240 CFRUNLOOPISCALLINGOUTTOASOURCE0PERFORMFUNCTION + 24 4 CoreFoundation 0x1a8f81140 CFRunLoopDoSource0 + 204 5 CoreFoundation 0x1a8f80488 CFRunLoopDoSources0 + 256 6 CoreFoundation 0x1a8f7aa40 CFRunLoopRun + 776 7 CoreFoundation 0x1a8f7a200 CFRunLoopRunSpecific + 572 8 GraphicsServices 0x1bf075598 GSEventRunModal + 160 9 UIKitCore 0x1ab840004 -[UIApplication run] + 1052 10 UIKitCore 0x1ab8455d8 UIApplicationMain + 164
29
1
12k
Oct ’20
Disable Scribble in UITextView
There are use cases where someone who's using an Apple Pencil may not want to enter text via Scribble. A simple example is writing "UIViewController" in a text view is unlikely to be successful. I'd like to disable Scribble in this case and let the keyboard become the input mechanism. (Disabling Scribble system-wide in Settings is both cumbersome and overkill.) The closest I can come to making this happen is by adding a UIScribbleInteraction on a UITextView and returning false when scribbleInteraction(shouldBeginAt:) is called. This disables Scribble on the text view, and prevents writing from being converted into text, but the input widget still appears on screen and isn't very useful. Here is a sample project that demonstrates the problem: http://files.iconfactory.net/craig/bugs/Scribbler.zip Hopefully, I'm doing something wrong here. If not, I'm happy to submit this as a FB. -ch
3
0
2.7k
Jun ’21
ASIdentifierManager.advertisingIdentifier hanging
Is there any threading assumption/requirement for ASIdentifierManager.advertisingIdentifier? Please see the complete issue and stack trace here. The main thread was waiting for the worker thread, which was blocked in ASIdentifierManager.advertisingIdentifier. Thread 68: 0 libsystem_kernel.dylib 0x188abf0f4 mach_msg_trap (in libsystem_kernel.dylib) + 8 1 libsystem_kernel.dylib 0x188abe5a0 mach_msg (in libsystem_kernel.dylib) + 72 2 libdispatch.dylib 0x188924880 _dispatch_mach_send_and_wait_for_reply (in libdispatch.dylib) + 500 3 libdispatch.dylib 0x188924d10 dispatch_mach_send_with_result_and_wait_for_reply$VARIANT$mp (in libdispatch.dylib) + 52 4 libxpc.dylib 0x188b8391c xpc_connection_send_message_with_reply_sync (in libxpc.dylib) + 204 5 Foundation 0x189aafa28 NSXPCCONNECTION_IS_WAITING_FOR_A_SYNCHRONOUS_REPLY (in Foundation) + 12 6 Foundation 0x189892f60 -[NSXPCConnection sendInvocation:orArguments:count:methodSignature:selector:withProxy:] (in Foundation) + 3608 7 CoreFoundation 0x188f3276c forwarding (in CoreFoundation) + 552 8 CoreFoundation 0x188f3475c forwarding_prep_0 (in CoreFoundation) + 92 9 CoreServices 0x1b1896ce4 -[LSApplicationWorkspace deviceIdentifierForAdvertising] (in CoreServices) + 160 10 AdSupport 0x198f70a60 -[ASIdentifierManager advertisingIdentifier] (in AdSupport) + 56 I don't see any thread related information in the document. I tried to recreate the scenario, but I could not reproduce the issue with the simplified test below. #import "ViewController.h" #import "AdSupport/AdSupport.h" #import "AppTrackingTransparency/AppTrackingTransparency.h" @interface ViewController () {  dispatch_queue_t _queue; } @end @implementation ViewController - (void)viewDidLoad {  [super viewDidLoad];  _queue = dispatch_queue_create("IdentityWorkerQueue", DISPATCH_QUEUE_SERIAL);  dispatch_set_target_queue(_queue,               dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0));  if (@available(iOS 14, *)) {   [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:    ^(ATTrackingManagerAuthorizationStatus status) {    NSLog(@"Status: %lu", (unsigned long)status);   }];  } } - (IBAction)action:(id)sender {  __block NSString *adId1 = nil;  dispatch_async(self->_queue, ^{   sleep(1);   adId1 = ASIdentifierManager.sharedManager.advertisingIdentifier.UUIDString;  });  __block NSString *adId2 = nil;  dispatch_sync(self->_queue, ^{   adId2 = adId1;  }); } @end Is there any threading assumption/requirement for ASIdentifierManager.advertisingIdentifier? For example, would it wait for the main thread to finish a certain task when an error happens?
2
1
984
Jun ’21
Widget not showing in "Widget Gallery"
Our app's widget often doesn't show up in the "Widget Gallery". Lots of our users complain about this issue. They can't see the widget in widget gallery after opening the app. In some cases, the widget does not appear in the widget gallery even after turning the phone off and on. I saw in another question that this is a bug. This bug will be fixed someday, but is there anything we can do before that?
3
0
1.7k
Jun ’21
Programmatically open popup in Safari Web Extension
I have a Safari web extension that needs the ability to open the popup when the user interacts with a modal coming from the content script. There is a native message handler that comes with the safari web extension when you first create it: import SafariServices import os.log class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling { func beginRequest(with context: NSExtensionContext) { let item = context.inputItems[0] as! NSExtensionItem let message = item.userInfo?[SFExtensionMessageKey] os_log(.default, "Received message from browser.runtime.sendNativeMessage: %@", message as! CVarArg) let response = NSExtensionItem() response.userInfo = [ SFExtensionMessageKey: [ "Response to": message ] ] print("hit") context.completeRequest(returningItems: [response], completionHandler: nil) } } I have the permissions to send a native message, I've seen some examples online where you can access the SFSafariApplication module from SafariServices and open the popover. But I can't seem to access SFSafariApplication in this module.
1
0
1.3k
Jul ’21
Swift Process with Psuedo Terminal (PTY)
Hi! I'm looking for some insight and guidance on using the Foundation.Process type with a PTY (Psuedo Terminal) so that the subprocess can accept input and behave as if it was running via a terminal. The reason for needing a PTY is that for programs like ssh or in my case (xcodes) which ask for user input including passwords, running these via Foundation.Process does not display the prompts to the user as the output is usually buffered (this works fine in the Xcode debugger console but when running via a real terminal that is buffered the prompts are never displayed in the terminal) Looking at other threads it seems like correct approach here is create a PTY and use the filehandles to attach to the Process. While I've got this to work to the point where prompts are now shown, I cant seem to figure out how to pass input back to the process as these are being controlled by the PTY. Here is my Process setup: let process = Process() // Setup the process with path, args, etc... // Setup the PTY handles var parentDescriptor: Int32 = 0 var childDescriptor: Int32 = 0 guard Darwin.openpty(&parentDescriptor, &childDescriptor, nil, nil, nil) != -1 else {   fatalError("Failed to spawn PTY") } parentHandle = FileHandle(fileDescriptor: parentDescriptor, closeOnDealloc: true) childHandle = FileHandle(fileDescriptor: childDescriptor, closeOnDealloc: true) process.standardInput = childHandle process.standardOutput = childHandle process.standardError = childHandle With this setup I then read the parent handle and output any result it gets (such as the input prompts): parentHandle?.readabilityHandler = { handle in   guard let line = String(data: handle.availableData, encoding: .utf8), !line.isEmpty else {     return   }   logger.notice("\(line)") } When process.run() is executed the program runs and I can see it asks for Apple ID: input in my terminal, however, when typing input into the terminal the process does not seem to react to this input. I've tried forwarding the FileHandle.standardInput: FileHandle.standardInput.readabilityHandler = { handle in   parentHandle?.write(handle.availableData) } But this doesn't seem to work either. What is the recommended way to setup a PTY with Foundation.Process for executing arbitrary programs and having them behave as if they were being run in a terminal context? Most of the resources I found online are about other languages and I'd like to stick with Foundation.Process vs. doing anything custom in C/C++ if possible as it just makes it easier to reason about / maintain. The resources for Swift on this topic are very lacking and I've checked out some open source projects that claim to do this but most require manually sending input to the PTY handle vs. accepting them from the user in a terminal. Any insight / help is very much appreciated!
9
0
3.5k
Aug ’21
App clip: userActivity.webpageURL is "https://example.com" for no reason
Hi, when trying to test my app clip, if there's no link in the _XCAppClipURL environment variable in the scheme (Or TestFlight invocation), userActivity.webpageURL is "https://example.com" even though I don't have this link anywhere in my project. This is my code for getting the link (I'm using UI: func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {     guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,        let incomingURL = userActivity.webpageURL else {       return       }       print("Incoming URL: \(incomingURL)")     } I removed _XCAppClipURL from the environment variables in the scheme and when I run the code I get: Incoming URL: https://example.com Is this a bug? How can I get rid of this https://example.com URL?
2
1
1.1k
Aug ’21
Querying imported files and folders on iOS using NSMetadataQuery
Hi all, I’m trying to use NSMetadataQuery on iOS to track changes to folders users have imported from elsewhere but, no matter what I try, I get no results. Following the documentation for searching file metadata with NSMetadataQuery, I’m creating a live query (albeit in Swift) and listening for […]QueryDidFinishGathering and […]QueryDidUpdate. The former fires, with no results, and the latter never fires. I’ve also tried following the Synchronizing Documents in the iCloud Environment example, adding the appropriate Ubiquity keys to my Info.plist and .entitlements file, with no change. I’m importing files and folders using SwiftUI’s View.fileImporter(isPresented:allowedContentTypes:allowsMultipleSelection:onCompletion:), but can’t see how I might security-scope the NSMetadataQuery’s execution (if that’s even a thing?). My test project is on GitHub, but the main parts are below… My query method: extension NSMetadataQueryUbiquitousExternalDocumentsTestApp { func findAccessibleFiles() { query.stop() fileMonitor?.cancel() fileMonitor = Publishers.MergeMany( [ .NSMetadataQueryDidFinishGathering, .NSMetadataQueryDidUpdate ].map { NotificationCenter.default.publisher(for: $0) } ) .receive(on: DispatchQueue.main) .sink { notification in query.disableUpdates() defer { query.enableUpdates() } foundItems = query.results as! [NSMetadataItem] print("Query posted \(notification.name.rawValue) with results: \(query.results)") } query.searchScopes = [ NSMetadataQueryAccessibleUbiquitousExternalDocumentsScope ] query.predicate = NSPredicate( format: "%K LIKE %@", argumentArray: [NSMetadataItemFSNameKey, "*"] ) query.sortDescriptors = [ NSSortDescriptor(key: NSMetadataItemFSNameKey, ascending: true) ] if query.start() { print("Query started") } else { print("Query didn't start for some reason") } } } Info.plist: […] <key>NSUbiquitousContainers</key> <dict> <key>iCloud.com.stevemarshall.AnnotateML</key> <dict> <key>NSUbiquitousContainerIsDocumentScopePublic</key> <true/> <key>NSUbiquitousContainerName</key> <string>AnnotateML</string> <key>NSUbiquitousContainerSupportedFolderLevels</key> <string>ANY</string> </dict> </dict> […]
3
0
2.1k
Sep ’21
Shortcut Donations Not Working
I am implementing a couple custom intents in my app. Having completed the implementation of the custom intent definitions and the intent handlers which presumably should be called on voice command based on the suggestedInovocationPhrase, I am getting stumped with just getting IOS to recognize my shortcut donation. While the shortcut donation is executed multiple times from the view that I am trying to create the shortcut for, it is never being displayed in the shortcut app or on my lock screen as having been donated. In my settings App, I have turned on (under Developer) "Display Recent Shortcuts" and "Display Donations on Lock Screen". Here is the code that is executing each time I think I am making a donation: - (NSUserActivity *) CreateMyShortcut {     NSUserActivity *newActivity = [[NSUserActivity alloc] initWithActivityType: kMyShortCutActivityType];          if (@available(iOS 12.0, *)) {         newActivity.persistentIdentifier = kMyShortCutActivityType;         newActivity.eligibleForSearch = TRUE;         newActivity.eligibleForPrediction = TRUE;                  CSSearchableItemAttributeSet *attributeSet = [[CSSearchableItemAttributeSet alloc] initWithContentType: UTTypeImage];                  newActivity.title = @"My Shortcut";         attributeSet.contentDescription = @"description";                  newActivity.suggestedInvocationPhrase = @"Create Widget";                  UIImage *image = [UIImage imageNamed:@"MyApp_Icon.jpg"];         NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];         attributeSet.thumbnailData = imageData;                  newActivity.contentAttributeSet = attributeSet;     }     return newActivity; } This is called from the view that I want to create the shortcut for with the following code:     // Donate a shortcut to allow Siri to assist with creating a parts list     NSUserActivity *activity = [[MyDonationManager sharedInstance] CreateMyShortcut];     NSLog(@"Donating Siri Shortcut");     [activity becomeCurrent]; Is there something else I need to do?
3
0
1.4k
Sep ’21
New iOS String Initializer can't get correct localized String for specific locale
I tried to build LocalizedKeyString using String's new Initializer. String(localized: "hello",locale: locale) When I change the language setting of the device, everything works as expected. However, when I try to get the string in a specific language using the specified Locale, I can only ever get the string in .current. String(localized: "hello",locale: Locale(identifier: "zh-cn"))     func getString(locale:Locale) -> String{          String(localized: "hello",locale: locale)     } If you change the display language of the project (or the language setting of the device), the text in Text is always displayed correctly. Text(getString(locale:.current)) However, the code in onAppear print(getString(locale:Locale(identifier: "zh-cn"))) It only displays the same content as Text, but not the specified Chinese. Is it my fault that the new Initializer The understanding is not correct, or the bug of String init(localized keyAndValue: String.LocalizationValue, table: String? = nil, bundle: Bundle? = nil, locale: Locale = .current, comment: StaticString? = nil) FB number: FB9675845
7
0
4.3k
Oct ’21
TextKit2: Relation between NSRange and NSTextRange
The way NSTextView is built it's inevitable to use NSTextStorage with TextKit2, however the NSAttributedString uses NSRange vs the TextKit2 family uses NSTextRange for text location, etc. What I struggle with is the relation between these two. I didn't find a convenient translation between these two. Is NSAttributedStrint NSRange length=1 equal to NSTextRange offset 1? I think it's not (at least it's not necessarily true for every NSTextContentManager. So my question is, given a NSTextRange, what is the corresponding NSRange in NSTextContentStorage.attributedString
4
0
2.0k
Nov ’21