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 ?
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
I am trying to follow the guidance for testing a Local Experience, as listed in the Testing Your App Clip’s Launch Experience - https://developer.apple.com/documentation/app_clips/testing_your_app_clip_s_launch_experience documentation. I have successfully created my App Clip target, and can confirm that running the App Clip on my device does launch the App Clip app as I expected. Further, I can successfully test the App Clip on device, by setting the _XCAppClipURL argument in the App Clip's scheme.
I would like to test a Local Experience. The documentation states that for testing Local Experiences;
To test your app clip’s invocation with a local experience, you don’t need to add the Associated Domains Entitlement, make changes to the Apple App Site Association file on your web server, or create an app clip experience for testing in TestFlight. Therefore, I should be able to configure a Local Experience with any desired domain in Settings -> Developer -> Local Experience, generate a QR code or NFC tag with that same URL, and the App Clip experience should appear. I have taken the following steps;
Built and run my App Clip on my local device.
In Settings -> Developer -> Local Experience, I have registered a new experience using a URL prefix https://somewebsite.com
Set my Bundle ID to com.mycompany.myapp.Clip, which exactly matches the Bundle Identifier, as listed in Xcode, under my App Clip target.
Generated a QR code which directs me to https://somewebsite.com
In theory, I believe I should be able to open the Camera app on my device, point the camera at the QR code, and the App Clip experience should appear. However, I received mixed experiences. 50% of the time, I receive a pop-up directing me to open https://somewebsite.com in Safari, the other 50% of the time, no banner or action occurs whatsoever.
Is this an issue anyone has faced before, or have I pursued these steps out of order?
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
i thought it is impossible to have CallKit show system UI for outgoing calls. but then i saw this:
"For incoming and outgoing calls, CallKit displays the same interfaces as the Phone app..."
https://developer.apple.com/documentation/callkit
how do i present it though? or is this a documentation error?
Hi, I have pretty trivial problem. So, I am trying to use URLSession network request but I am getting errors.
This code is in the shared file that works when I run it as app, but when I run it as AppClip it is not working. Running on the simulator is working even as AppClip.
Here is the code (pretty trivial):
let session = URLSession.shared
let url = URL(string: "https://learnappmaking.com/ex/users.json")!
let task = session.dataTask(with: url, completionHandler: { _, response, error in
print(error)
print(response)
})
task.resume()
I am getting this error:
2020-11-20 19:35:05.189273+0100 ExampleAppClip[14703:4633304] [Client] Updating selectors after delegate removal failed with: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service on pid 92 named com.apple.commcenter.coretelephony.xpc was invalidated from this process." UserInfo={NSDebugDescription=The connection to service on pid 92 named com.apple.commcenter.coretelephony.xpc was invalidated from this process.}
2020-11-20 19:35:05.363730+0100 ExampleAppClip[14703:4633299] [connection] nw_socket_connect [C1.1:3] connectx(8 (guarded), [srcif=0, srcaddr=<NULL>, dstaddr=104.27.132.57:443], SAE_ASSOCID_ANY, 0, NULL, 0, NULL, SAE_CONNID_ANY) failed: [65: No route to host]
2020-11-20 19:35:05.364100+0100 ExampleAppClip[14703:4633299] [connection] nw_socket_connect [C1.1:3] connectx failed (fd 8) [65: No route to host]
2020-11-20 19:35:05.364195+0100 ExampleAppClip[14703:4633299] [] nw_socket_connect connectx failed [65: No route to host]
2020-11-20 19:35:05.368229+0100 ExampleAppClip[14703:4633299] [connection] nw_socket_connect [C1.2:3] connectx(8 (guarded), [srcif=0, srcaddr=<NULL>, dstaddr=104.27.133.57:443], SAE_ASSOCID_ANY, 0, NULL, 0, NULL, SAE_CONNID_ANY) failed: [65: No route to host]
2020-11-20 19:35:05.368424+0100 ExampleAppClip[14703:4633299] [connection] nw_socket_connect [C1.2:3] connectx failed (fd 8) [65: No route to host]
2020-11-20 19:35:05.368484+0100 ExampleAppClip[14703:4633299] [] nw_socket_connect connectx failed [65: No route to host]
2020-11-20 19:35:05.370781+0100 ExampleAppClip[14703:4633299] [connection] nw_socket_connect [C1.3:3] connectx(8 (guarded), [srcif=0, srcaddr=<NULL>, dstaddr=172.67.210.249:443], SAE_ASSOCID_ANY, 0, NULL, 0, NULL, SAE_CONNID_ANY) failed: [65: No route to host]
2020-11-20 19:35:05.370989+0100 ExampleAppClip[14703:4633299] [connection] nw_socket_connect [C1.3:3] connectx failed (fd 8) [65: No route to host]
2020-11-20 19:35:05.371054+0100 ExampleAppClip[14703:4633299] [] nw_socket_connect connectx failed [65: No route to host]
2020-11-20 19:35:05.372142+0100 ExampleAppClip[14703:4633299] Connection 1: received failure notification
2020-11-20 19:35:05.372241+0100 ExampleAppClip[14703:4633299] Connection 1: failed to connect 1:65, reason -1
2020-11-20 19:35:05.372291+0100 ExampleAppClip[14703:4633299] Connection 1: encountered error(1:65)
2020-11-20 19:35:05.374764+0100 ExampleAppClip[14703:4633300] Task <3C72DFED-F839-4BD2-9FE2-CC0B8BB7090F>.<1> HTTP load failed, 0/0 bytes (error code: -1004 [1:65])
2020-11-20 19:35:05.383016+0100 ExampleAppClip[14703:4633299] Task <3C72DFED-F839-4BD2-9FE2-CC0B8BB7090F>.<1> finished with error [-1004] Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={_kCFStreamErrorCodeKey=65, NSUnderlyingError=0x282ecc5a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_kCFStreamErrorCodeKey=65, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <3C72DFED-F839-4BD2-9FE2-CC0B8BB7090F>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
&#9;&#9;"LocalDataTask <3C72DFED-F839-4BD2-9FE2-CC0B8BB7090F>.<1>"
), NSLocalizedDescription=Could not connect to the server., NSErrorFailingURLStringKey=https://learnappmaking.com/ex/users.json, NSErrorFailingURLKey=https://learnappmaking.com/ex/users.json, _kCFStreamErrorDomainKey=1}
Optional(Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={_kCFStreamErrorCodeKey=65, NSUnderlyingError=0x282ecc5a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_kCFStreamErrorCodeKey=65, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <3C72DFED-F839-4BD2-9FE2-CC0B8BB7090F>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
&#9;&#9;"LocalDataTask <3C72DFED-F839-4BD2-9FE2-CC0B8BB7090F>.<1>"
), NSLocalizedDescription=Could not connect to the server., NSErrorFailingURLStringKey=https://learnappmaking.com/ex/users.json, NSErrorFailingURLKey=https://learnappmaking.com/ex/users.json, _kCFStreamErrorDomainKey=1})
nil
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
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?
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?
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 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?