Foundation

RSS for tag

Access essential data types, collections, and operating-system services to define the base layer of functionality for your app using Foundation.

Posts under Foundation tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

FileDocument - open another file in the same directory as selected file
I'm working on a macOS app where my file format can include other files (think #include in C/C++). When opening a file with SwiftUI's document-based APIs (i.e., FileDocument), is there a way to get access to those other files? Alternatively, is there a way I could "open" the file's directory, similar to how Xcode opens the directory that a .xcodeproj is located? I don't mind falling back to older Cocoa APIs if this is too obscure for the shiny new stuff :)
3
0
550
2w
AttributedString (without NS prefix) and Genmoji
My app uses AttributedString for both text formatting and storage using MarkdownDecodableAttributedStringKey. The new API for Genmoji looks very interesting but I don't see an AttributeScope for it. Is it possible to work around this and stick with AttributedString, am I in the wrong room or should I send in an enhancement request via Feedback Assistant? Thanks a lot for your time!
2
0
219
2w
Screen Sleep Issue When Removing Vision Pro
Hello VisionOS Developer Community, I am currently working on a demo application for VisionOS, tailored for the Vision Pro. In my application, I have implemented a feature to prevent the screen from sleeping using the following code: UIApplication.shared.isIdleTimerDisabled = true This works perfectly on iOS, ensuring the screen remains active regardless of other system settings. However, I've run into a snag with VisionOS. Even with isIdleTimerDisabled set to true, the screen still sleeps when I take off the Vision Pro.
0
0
147
2w
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
7.7k
2w
IOS 18.0 Beta - „Hidden“ Feature ‚Bug‘
Hi, I’ve identified an issue with the “hidden” feature that was added to IOS 18.0. The issue causes the stuff you would like to hide, to become not so hidden anymore. This due to the fact that the apps you are trying to hide are still visible in other parts of the phone. Examples are: Battery consumption location services (and A number of other features in privacy & securit) -Siri -> Apps. I kindly ask the development team to go through the actual feature and identify the possible locations the apps you try to huse could be visible. thanks jorn
2
0
255
3w
Color asset test not working due to color not being loaded when test conditions are evaluated
I've written a Swift package plugin to add the colours provided in the asset bundles in an extension of the SwiftUI Color type but I'm having difficulties testing this since the bundle and/or colour that is in the asset catalogs are not yet loaded when XCTest goes to evaluate the test conditions. Here is my test code: (colours are just random colours, some derive from macOS colour picker; also, the new static method is functionality that I added and is not present in the existing Color APIs) final class TestCase: XCTestCase { func testBanana() { XCTAssertEqual(Color.banana, Color.new(from: "FEFC78")!) } func testAlexsColor() { XCTAssertEqual(Color.alexsColor, Color.new(from: "0432FF")!) } func testMaximumPowerColor() { XCTAssertEqual(Color.maximumPower, Color.new(from: "FF2600")!) } func testLongNameColor() { XCTAssertEqual(Color.reallyLongNameThatJustKeepsGoingOnAndOnAndOnAndOn, Color.new(from: "AAA000")) } } Here is an example error message that I get when I run the test: testBanana(): XCTAssertEqual failed: ("NamedColor(name: "Banana", bundle: Optional(NSBundle </Users/trevorhafner/Library/Developer/Xcode/DerivedData/TransportBase-cbagdabrompfzofwkimswvlsincu/Build/Products/Debug/TransportBaseTests.xctest/Contents/Resources/TransportBase_TransportBaseTests.bundle> (not yet loaded)))") is not equal to ("#FEFC78FF") Here is the autogenerated code that my Swift Package Plugin creates: #if canImport(SwiftUI) import SwiftUI import Foundation @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public extension Color { static let banana = Color("Banana", bundle: .module) static let alexsColor = Color("Alex's Color", bundle: .module) static let reallyLongNameThatJustKeepsGoingOnAndOnAndOnAndOn = Color("really long name that just keeps going on and on and on and on", bundle: .module) static let maximumPower = Color("Maximum Power", bundle: .module) } #endif Does anyone know how to somehow instruct the bundle or the Color to load such that the comparison can be made correctly between the two colours?
4
1
1.6k
3w
App cannot upgrade to http/3 when running on iOS 16
My team are now testing http/3 support in our app and backend. It looks strange to me how the behaviour is different between iOS 15.7.3 and 16.x (now 16.6). It is a default URLSession config and just a regular URLRequest, with no assumesHTTP3Capable flag set. I observe the protocol in use with both collecting URLSessionTaskMetrics and the Network instrument. On 15.7.3 the 1st request is done using h2, the network subsystem caches the Alt-Svc header (per host I suppose). Several seconds pass and then when I issue the same 2nd request a new connection is established and the protocol is upgraded to h3. This is all fine and as described in the documentation or wwdc videos. However, when I take the same steps with a device running e.g. iOS 16.5.1 I see that the protocol is never upgraded to h3. Neither a longer timeout nor an app relaunch make any difference. Interestingly, on my Ventura desktop the same url is also handled differently: h3 by Chrome but always h2 by Safari. In the mobile Safari on iOS 16, I'm also always shown HTTP/2 on e.g. the cloudflare status page for QUIC. What can be the reason for such behaviour on iOS 16 and Apple platforms in general? PS. I've tried running the app with CFNETWORK_DIAGNOSTICS but found no useful log messages to clarify problems with QUIC. Is there still a way to better diagnose such a problem?
3
0
1k
3w
Cordova based app not working after updating iOS to 17.5.1
After updating iOS, my Cordova app behaves incorrectly after receiving a voip push. When a push notification is received, my application launches CallKit, displays the Native Dialer screen and starts other necessary services. Until 17.5.1 (possibly 17.5) everything worked correctly. All services and sockets were established/ connected and working. After updating iOS to 17.5, the application crashes, and while voice connection is established the app is no longer active. Xcode logs have these error messages: Invalidating grant <invalid NS/CF object> failed Type: Error | Timestamp: 2024-06-20 13:27:44.719601+02:00 | Process: MyApp | Library: WebKit | Subsystem: com.apple.WebKit | Category: ProcessCapabilities | TID: 0x3a4929 Invalidating grant <invalid NS/CF object> failed Type: Error | Timestamp: 2024-06-20 13:27:44.732219+02:00 | Process: MyApp | Library: WebKit | Subsystem: com.apple.WebKit | Category: ProcessCapabilities | TID: 0x3a4929 Invalidating grant <invalid NS/CF object> failed Type: Error | Timestamp: 2024-06-20 13:27:44.733996+02:00 | Process: MyApp | Library: WebKit | Subsystem: com.apple.WebKit | Category: ProcessCapabilities | TID: 0x3a4929 I am using: Cordova iOS: 6.2 iOS 17.5.1 Can anyone please help?
3
1
961
3w
Document Access Codes and Settings
Currently, there must be a request for access to documents with xcode, but we do not request access. Added NSDocumentDirectoryUsageDescription to info. import SwiftUI import AVFoundation import UniformTypeIdentifiers struct ContentView: View { @State private var audioPlayer: AVAudioPlayer? @State private var isPlaying = false @State private var currentFileName: String = "No file selected" @State private var showingDocumentPicker = false @State private var songList: [String] = UserDefaults.standard.stringArray(forKey: "SavedSongs") ?? [] @State private var currentSongIndex: Int = 0 var body: some View { VStack { Text(currentFileName) .font(.headline) .padding() List { ForEach(songList, id: \.self) { song in HStack { Text(song) .onTapGesture { loadAndPlaySong(named: song) } Spacer() Button(action: { removeSong(named: song) }) { Image(systemName: "trash") .foregroundColor(.red) } } } } .listStyle(PlainListStyle()) HStack(spacing: 10) { Button(action: { showingDocumentPicker = true }) { Text("Load") .font(.system(size: 12)) .frame(width: 50, height: 25) .background(Color.blue) .foregroundColor(.white) .cornerRadius(5) } .padding(.bottom, 20) } .padding() .sheet(isPresented: $showingDocumentPicker) { DocumentPicker(audioPlayer: $audioPlayer, currentFileName: $currentFileName, songList: $songList) } .onAppear { if !songList.isEmpty { loadAndPlaySong(named: songList[currentSongIndex]) } } } func playSong() { audioPlayer?.play() isPlaying = true } func pauseSong() { audioPlayer?.pause() isPlaying = false } func stopSong() { audioPlayer?.stop() audioPlayer?.currentTime = 0 isPlaying = false } func nextSong() { currentSongIndex = (currentSongIndex + 1) % songList.count loadAndPlaySong(named: songList[currentSongIndex]) } func previousSong() { currentSongIndex = (currentSongIndex - 1 + songList.count) % songList.count loadAndPlaySong(named: songList[currentSongIndex]) } func loadAndPlaySong(named songName: String) { guard let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } let fileURL = documentsURL.appendingPathComponent(songName) do { audioPlayer = try AVAudioPlayer(contentsOf: fileURL) audioPlayer?.prepareToPlay() currentFileName = songName playSong() } catch { print("Error loading file: \(error.localizedDescription)") } } func removeSong(named songName: String) { songList.removeAll { $0 == songName } UserDefaults.standard.set(songList, forKey: "SavedSongs") } } struct DocumentPicker: UIViewControllerRepresentable { @Binding var audioPlayer: AVAudioPlayer? @Binding var currentFileName: String @Binding var songList: [String] func makeCoordinator() -> Coordinator { return Coordinator(self) } func makeUIViewController(context: Context) -> UIDocumentPickerViewController { let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.audio]) documentPicker.delegate = context.coordinator return documentPicker } func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {} class Coordinator: NSObject, UIDocumentPickerDelegate { let parent: DocumentPicker init(_ parent: DocumentPicker) { self.parent = parent } func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { guard let url = urls.first else { return } do { if url.startAccessingSecurityScopedResource() { defer { url.stopAccessingSecurityScopedResource() } let fileName = url.lastPathComponent let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let destinationURL = documentsURL.appendingPathComponent(fileName) if FileManager.default.fileExists(atPath: destinationURL.path) { try FileManager.default.removeItem(at: destinationURL) } try FileManager.default.copyItem(at: url, to: destinationURL) parent.audioPlayer = try AVAudioPlayer(contentsOf: destinationURL) parent.audioPlayer?.prepareToPlay() parent.currentFileName = fileName if !parent.songList.contains(fileName) { parent.songList.append(fileName) UserDefaults.standard.set(parent.songList, forKey: "SavedSongs") } } else { print("I can't get file access.") } } catch { print("An error occurred while loading the file: \(error.localizedDescription)") } } func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { } } }
0
0
172
3w
Permission denied: GenerativeFunctionMetrics
A sample of some error messages that are presented in the Xcode log for executon of a program. There is nothing in the messages that will help identify a component as the origin of the message, nor is there a locatable derinition for the various labels and fields of the text. What component or even framework does this set of messages originate? Your search engine is useless because it returns gibberish. It doesn’t even follow the common behavior of SEARCH ENGINES because it takes label strings compounded from common words and searches for the common word instead of using the catenated string that is the internal variable name that is in the text. 2024-06-22 19:45:58.089943-0500 RoomPlanExampleApp[733:30145] [ClientDonation] (+[PPSClientDonation isRegisteredSubsystem:category:]) Permission denied: GenerativeFunctionMetrics / ANEInferenceOperationPrepareForEncode. I am looking for a definition of the error with a way to locate the context in which the error occurs. 2024-06-22 19:45:58.089967-0500 RoomPlanExampleApp[733:30145] [ClientDonation] (+[PPSClientDonation sendEventWithIdentifier:payload:]) Invalid inputs: payload={ aneModelPath = "/System/Library/PrivateFrameworks/RoomScanCore.framework/PrecompiledModels/lcnn_floorplan_model.bundle/H14G.bundle/main/segment_0__ane/net.hwx"; bundleIdentfier = "com.example.apple-samplecode.RoomPlanExampleApp9QSS565686"; } 2024-06-22 19:45:58.094770-0500 RoomPlanExampleApp[733:30145] [ClientDonation] (+[PPSClientDonation sendEventWithIdentifier:payload:]) Invalid inputs: payload={ bundleIdentfier = "com.example.apple-samplecode.RoomPlanExampleApp9QSS565686"; e5FunctionName = main; numSegments = 1; }
1
0
264
3w
Issue with Background Serial Communication Using Type-C on iPad Pro
Hello, I am experiencing an issue with background serial communication on my iPad Pro when using a Type-C connection to an external device. Specifically, when the app is inactive, in low power mode, or when the screen is locked (i.e., not active), the communication with the external device is interrupted. However, this problem does not occur when using a Lightning cable on my iPad Mini. In that setup, the background serial communication works seamlessly under the same conditions. Has anyone encountered a similar issue or have any insights into why the behavior differs between Type-C and Lightning connections? Any suggestions or workarounds would be greatly appreciated. Thank you!
1
0
201
3w
iOS 17.4.1 Crash with WebCore "cache_remove_all"
Our iOS 17.4.1 users are experiencing a crash when we try to convert Markdowns to HTML. We're wondering what could be the trigger for this crash 💥. we would love to get some help. Here is the full stack: Crashed: WebThread 0 WebCore 0x2ee8 <redacted> + 20 1 WebCore 0x15df7d0 <redacted> + 11068 2 WebCore 0x191b6b0 <redacted> + 264 3 WebCore 0x15e0e7c <redacted> + 784 4 WebCore 0x1e1a01c WebCore::LocalFrame::~LocalFrame() + 548 5 WebCore 0x1e1a760 WebCore::LocalFrame::~LocalFrame() + 16 6 WebCore 0x1e5470c WebCore::Page::~Page() + 7264 7 WebKitLegacy 0xb65e8 __29-[WebView(WebPrivate) _close]_block_invoke + 372 8 WebCore 0x214d070 <redacted> + 648 9 CoreFoundation 0x3762c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 10 CoreFoundation 0x368a8 __CFRunLoopDoSource0 + 176 11 CoreFoundation 0x350b8 __CFRunLoopDoSources0 + 340 12 CoreFoundation 0x33d88 __CFRunLoopRun + 828 13 CoreFoundation 0x33968 CFRunLoopRunSpecific + 608 14 WebCore 0xe90110 <redacted> + 780 15 libsystem_pthread.dylib 0x2a90 _pthread_start + 136 16 libsystem_pthread.dylib 0x1fcc thread_start + 8 com.apple.uikit.datasource.diffing 0 libsystem_kernel.dylib 0x249c __psynch_cvwait + 8 1 libsystem_pthread.dylib 0x1590 _pthread_cond_wait + 1228 2 JavaScriptCore 0x7d5f8 ***::ThreadCondition::timedWait(***::Mutex&, ***::WallTime) + 160 3 JavaScriptCore 0x51d78 ***::ParkingLot::parkConditionallyImpl(void const*, ***::ScopedLambda<bool ()> const&, ***::ScopedLambda<void ()> const&, ***::TimeWithDynamicClockType const&) + 2072 4 JavaScriptCore 0x42468 ***::LockAlgorithm<unsigned char, (unsigned char)1, (unsigned char)2, ***::EmptyLockHooks<unsigned char> >::lockSlow(***::Atomic<unsigned char>&) + 216 5 WebCore 0xe8da54 <redacted> + 280 6 WebCore 0xe8ea38 WebThreadLock + 132 7 UIFoundation 0xdb68c -[NSHTMLReader _loadUsingWebKit] + 1448 8 UIFoundation 0xdc234 -[NSHTMLReader attributedString] + 24 9 UIFoundation 0x83c88 _NSReadAttributedStringFromURLOrDataCommon + 6440 10 UIFoundation 0x7ed34 _NSReadAttributedStringFromURLOrData + 288 11 UIFoundation 0x7ebac -[NSAttributedString(NSAttributedStringUIFoundationAdditions) initWithData:options:documentAttributes:error:] + 148 ...
1
0
197
Jun ’24
Error when downloading files with multiple background urlsession
Hi, I am trying to download multiple files in background (using multiple background urlsession). I initiate the download on click of a button and push the app to background where the download should happen. I am getting the following error: Error Domain=NSCocoaErrorDomain Code=4 "“CFNetworkDownload_EYp3BT.tmp” couldn’t be moved to “Documents” because either the former doesn’t exist, or the folder containing the latter doesn’t exist." UserInfo={NSSourceFilePathErrorKey=/private/var/mobile/Containers/Data/Application/85AEEB4F-1512-4C0C-8B04-C9C73634CC49/Library/Caches/com.apple.nsurlsessiond/Downloads/com.mycompany.DownloadMultipleFilesTestApp/CFNetworkDownload_EYp3BT.tmp, NSUserStringVariant=(\n Move\n), NSDestinationFilePath=/var/mobile/Containers/Data/Application/85AEEB4F-1512-4C0C-8B04-C9C73634CC49/Documents/file-441966.pdf, NSFilePath=/private/var/mobile/Containers/Data/Application/85AEEB4F-1512-4C0C-8B04-C9C73634CC49/Library/Caches/com.apple.nsurlsessiond/Downloads/com.mycompany.DownloadMultipleFilesTestApp/CFNetworkDownload_EYp3BT.tmp, NSUnderlyingError=0x28155f900 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}} In my sample code attached here i am trying with 500 background urlsession (one download task per each url session) I have implemented the required methods: application(_:handleEventsForBackgroundURLSession:completionHandler) and urlSessionDidFinishEvents forBackgroundURLSession:) I have found that the error happens because of two callbacks to urlSession(_:downloadTask:didFinishDownloadingTo:) where i move the file from temporary location to a location in my app's documents directory. The first time the file is present at the location, but for the second callback (with same urlsession id, task id and location values) to urlSession(_:downloadTask:didFinishDownloadingTo:) the file isnt present there and so the move fails. Can someone please explain this erratic behaviour ? Is this a known issue with URLSession ? For a repro, you can use the code attached above, test on a physical device without running app from xcode ie launch the app from phone's home screen, click on the download button and send the app to background. Check logs in the console app on mac Test environment: iPhone 8plus with iOS 16.7.8
3
9
368
Jun ’24
Privacy Solution for Apps in iOS (Please Read)
Hear me out, developers at Apple! You've done an amazing job with privacy so far. The introduction of ContactAccess and the Contact Access Button this year is truly an amazing work of art. Well done. However, all the way back to the first iPhone I got in 2007, I wished Apple would make API's available to access the users installed apps (in a privacy way). This would (further) open up apps in the category of App Managers and App Launchers. Back in the early days the trick was to use deep link, but that was also awkward, since you needed to know the deeplink upfront and the apps needed to support it. Not ideal. It also had a side effect that Apple noticed, that evil party's used it to scan your device to know which apps you had installed and create a profile from that. Apple fixed that by using LSApplicationQueriesSchemes. Now you have to tell the App upfront which apps you will be calling (up to 50), or use Universal Link to be freed from this limitation again. Again not ideal. Why not turn it around and let the user decide? User central. Imagine an App Launcher app. There is a button in the launcher app where you as a user can click on to add an app. It calls an api available from Apple to launch a privacy shielded sheet with the apps the user got installed on its device. These are not exposed to the launcher app. When the user clicks on the installed app (or apps) it likes to add, the launcher app will get identifiers to launch the app. That's it. This would be limited access, perhaps the api could also expose full access, so permission could be granted once and the app will get all identifiers available. The choice will be up to the user. One step further, but this would be more nice-to-have, is the ability to access meta data of the app, such as icon, title, last launched, app size, etc. This way App Launchers can make decisions such as putting the most recent launched app in front or App Managers can use this to decide which apps you are not using and can advise to remove them to clean up space. Love to hear everyone's opinion. So let it be the start of the discussion.
3
0
315
Jun ’24
User Data is getting randomly deleted
this is an email I have sent to Apple with no luck: Dear Apple Developer Support Team, I am writing to seek urgent assistance with a persistent issue I have been encountering with Xcode. For several months now, every time I connect my iPhone to Xcode for development purposes, it automatically overwrites the user data of my apps with an old, seemingly random container. This issue is severely impacting my ability to continue development, as I cannot test new changes effectively. This occurs since a few months in every iOS and Xcode/macOS Version. I tried it with different Apps and Devices. Sometimes the entire Container (Documents) gets read only access so no new data can be created or changed by the user. I frequently used the replace container feature on Xcode so maybe this has something to do with it. This problem persists despite numerous attempts to resolve it on my end. I am at a critical point in my development timeline, and it is crucial for me to resolve this as soon as possible. Could you please advise on the next steps I should take to address this issue? If there are any logs or further information you require, I am more than willing to provide them. Thank you for your attention to this matter. I look forward to your prompt response and hope for a resolution soon. Best regards, Victor Lobe
7
0
609
Jun ’24