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.
General
RSS for tagDelve 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
Is it possible to write an iOS app or app extension to block an incoming call based on the area code (or some other portion of the incoming call number)?
Using SwiftUI, I want to determine 12 hour vs 24 hour from system settings
With the announcement of the new Apple Translate app and offline support, are there any URL schemes that we can use in our apps to send text to the Translate app and have it open and translate the sent text?
Hey guys,
Is there a native bridge between a PKStrokePath and other path objects like CGPath, UIBezierPath or even SwiftUI Path ?
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)
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.
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
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?
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.
on iOS, I want to add up undo/redo and a close button. On ipadOS, I only need to add a close button
What’s your experience in adding a close button to the ToolPicker? Or at least have the position of the window so I can add an overlapping box (even on floating).
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!
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?
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>
[…]
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
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
I have received two strange crash reports from an iPad11,7 running iPadOS 15.1 and an iPad11,2 running iPadOS 15.2.
On both occasions, the crashed thread calls CFURLRequestSetMainDocumentURL, which in turn calls _dispatch_source_set_runloop_timer_4CF in libdispatch, after which the application crashes with SIGSEGV and SEGV_MAPERR.
The crashed thread's call stack is displayed below. Full crash logs are attached as well. What could this be?
Exception Type: SIGSEGV
Exception Codes: SEGV_MAPERR at 0x21d
Crashed Thread: 20
Thread 20 Crashed:
0 libdispatch.dylib 0x00000001829e1784 _dispatch_source_set_runloop_timer_4CF + 36
1 CFNetwork 0x00000001834fc824 CFURLRequestSetMainDocumentURL + 2240
2 CFNetwork 0x00000001836b89a8 _CFNetworkErrorGetLocalizedDescription + 693652
3 CFNetwork 0x00000001834fdb1c CFURLRequestSetMainDocumentURL + 7096
4 CFNetwork 0x00000001834f3c34 CFURLRequestSetURL + 9668
5 libdispatch.dylib 0x00000001829ca914 _dispatch_call_block_and_release + 28
6 libdispatch.dylib 0x00000001829cc660 _dispatch_client_callout + 16
7 libdispatch.dylib 0x00000001829d3de4 _dispatch_lane_serial_drain + 668
8 libdispatch.dylib 0x00000001829d498c _dispatch_lane_invoke + 440
9 libdispatch.dylib 0x00000001829d5c74 _dispatch_workloop_invoke + 1792
10 libdispatch.dylib 0x00000001829df1a8 _dispatch_workloop_worker_thread + 652
11 libsystem_pthread.dylib 0x00000001f1eea0f4 _pthread_wqthread + 284
12 libsystem_pthread.dylib 0x00000001f1ee9e94 start_wqthread + 4
second_crashlog.txt
report-2517628380750009999-e4d7ea06-6f22-4b7e-b129-045599e1dee5.txt
Hello, sometimes if I use NSMetadataQuery to obervse my file changes on macOS, it crash for this reason, its odd and i have no clue for this problem becuse in my code I never get results using index, anyone help? thanks!
Application Specific Information:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[_NSMetadataQueryResultArray objectAtIndex:]: index (251625) out of bounds (251625)'
terminating with uncaught exception of type NSException
abort() called
I am trying to write a safari web extension that redirects users to Y URL if they type X URL without ever loading the X URL.
The piece of code that I have attached below works smoothly on chrome, but not on safari.
background.js
function onBeforeNavigate(event) {
const redirectURL = "https://google.com/"
chrome.tabs.update(event.tabId, { url: redirectURL })
}
chrome.webNavigation.onBeforeNavigate.addListener(onBeforeNavigate,{
url: [
{urlMatches: "https://girlcodeit.com/*"},
{urlMatches: "http://girlcodeit.com/*"}
]
})
manifest.json
"manifest_version": 2,
"name": "",
"description": "",
"version": "1.0",
"background": {
"scripts": [
"background.js"
]
},
"permissions": [
"webNavigation",
"tabs"
]
}
I have tried writing browser.tabs.update and just tabs.update in place of chrome.tabs.update in safari version, no change.
I want to achieve the redirection anyhow through a safari web extension, please suggest changes in this one or share any other approaches.
webRequestBlocking is not supported by Safari, so that doesn't work either.
With "Automatically Manage Signing" enabled in Signing & Capabilities I got a message when uploading to the App Store complaining that my provisioning profile was missing Family Control capabilities.
I do have the capability enabled in XCode, and I can deploy directly to devices to see that the app works correctly (that is, it has the capability).
Further, I can see the same capability checked in the App Id under my developer profile.
Further, if I generate a profile manually it claims to include Family Controls in the info screen.
But still it won't let me upload the app.
I've tried:
deleting all automatically generated profiles and regenerating them.
adding and removing the capability in Xcode and in the App Id
generating a manual provisioning profile and downloading it (this one complains about the missing capability when I download it).
Any ideas?