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

Array<NSNumber> not working for EKRecurringRule in EventKit
I am having an issue here with the NSNumber Type using with SwiftUI and I am not sure what I am doing wrong here? @State private var recurringMonthsTest: NSNumber = 1` let rule = EKRecurrenceRule( recurrenceWith: recurringOn, interval: recurringInterval, daysOfTheWeek: [EKRecurrenceDayOfWeek.init(EKWeekday.monday)], daysOfTheMonth: [], monthsOfTheYear: [recurringMonthsTest], weeksOfTheYear: [], daysOfTheYear: [], setPositions: nil, end: EKRecurrenceEnd.init(occurrenceCount: 8)) } Here is some basic Code to explain the issue, if you look at the above code it works well, I can also put 2 or more NSNumber single values inside the rule. But if I start to use the Array as below let recurringMonthsTest2: Array<NSNumber> = [recurringMonthsTest, recurringMonthsTest1] let rule = EKRecurrenceRule( recurrenceWith: recurringOn, interval: recurringInterval, daysOfTheWeek: [EKRecurrenceDayOfWeek.init(EKWeekday.monday)], daysOfTheMonth: [], monthsOfTheYear: [recurringMonthsTest2], weeksOfTheYear: [], daysOfTheYear: [], setPositions: nil, end: EKRecurrenceEnd.init(occurrenceCount: 8)) } It doesn't compile and I get the below error which I don't understand. `Cannot convert value of type 'Array' to expected element type 'Array.ArrayLiteralElement' (aka 'NSNumber') As I understand both are of the same value but why they don't compile? I tried already several versions like [NSNumber] = [] but everything is failing... What am I doing wrong here, can anyone help?
1
0
357
Aug ’24
iOS 18 beta 5 NSAttributedString Crash
There have been hundreds of the same crashes occurring every day recently. The crash stack information I have collected is as follows: AppStoreTools: 15F31e AppVariant: 1:iPhone15,4:17 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: com.***.***.xxxx [1125] Date/Time: 2024-08-12 06:28:47.8121 +0800 Launch Time: 2024-08-12 06:24:53.4931 +0800 OS Version: iPhone OS 18.0 (22A5326f) Release Type: Beta Baseband Version: 2.16.02 Report Version: 104 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: SIGNAL 6 Abort trap: 6 Terminating Process: xxxx [1439] Triggered by Thread: 0 Last Exception Backtrace: 0 CoreFoundation 0x18f65c08c __exceptionPreprocess + 164 (NSException.m:249) 1 libobjc.A.dylib 0x18c9632e4 objc_exception_throw + 88 (objc-exception.mm:356) 2 Foundation 0x18e2424cc -[NSRLEArray objectAtIndex:effectiveRange:] + 172 (NSAttributedString.m:1408) 3 WebKit 0x1a59d87a0 __70-[WKContentView(WKInteraction) setAttributedMarkedText:selectedRange:]_block_invoke + 156 (WKContentViewInteraction.mm:6305) 4 WebKit 0x1a59d7fec -[WKContentView(WKInteraction) setAttributedMarkedText:selectedRange:] + 136 (WKContentViewInteraction.mm:6297) 5 UIKitCore 0x192db41e0 -[UIResponder(UITextInput_Internal) _setAttributedMarkedText:selectedRange:] + 120 (UITextInput_Internal.m:1735) 6 UIKitCore 0x192a53518 -[UIKBInputDelegateManager setAttributedMarkedText:selectedRange:] + 152 (UIKBInputDelegateManager.m:0) 7 UIKitCore 0x192741050 -[_UIKeyboardStateManager _setAttributedMarkedText:selectedRange:inputString:lastInputString:searchString:compareAttributes:] + 696 (_UIKeyboardStateManager.m:7217) 8 UIKitCore 0x1927407e8 -[_UIKeyboardStateManager setMarkedText:selectedRange:inputString:lastInputString:searchString:candidateOffset:liveConversionSegments:highlighSegmentIndex:] + 692 (_UIKeyboardStateManager.m:7118) 9 UIKitCore 0x192760e38 -[_UIKeyboardStateManager assertIntermediateText:] + 200 (_UIKeyboardStateManager.m:15075) 10 UIKitCore 0x1927440c4 -[_UIKeyboardStateManager syncKeyboardToConfiguration:] + 144 (_UIKeyboardStateManager.m:7934) 11 UIKitCore 0x192745040 __64-[_UIKeyboardStateManager handleKeyboardInput:executionContext:]_block_invoke_2 + 988 (_UIKeyboardStateManager.m:8101) 12 UIKitCore 0x192259834 -[UIKeyboardTaskEntry execute:] + 208 (UIKeyboardTaskQueue.m:869) 13 UIKitCore 0x1922596c8 -[UIKeyboardTaskQueue continueExecutionOnMainThread] + 324 (UIKeyboardTaskQueue.m:447) 14 Foundation 0x18e2b783c __NSThreadPerformPerform + 264 (NSThread.m:1084) 15 CoreFoundation 0x18f62f088 CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 28 (CFRunLoop.c:1950) 16 CoreFoundation 0x18f62f01c __CFRunLoopDoSource0 + 176 (CFRunLoop.c:1994) 17 CoreFoundation 0x18f62cb08 __CFRunLoopDoSources0 + 244 (CFRunLoop.c:2031) 18 CoreFoundation 0x18f62bd04 __CFRunLoopRun + 840 (CFRunLoop.c:2949) 19 CoreFoundation 0x18f62b5b8 CFRunLoopRunSpecific + 572 (CFRunLoop.c:3414) 20 GraphicsServices 0x1db3331c4 GSEventRunModal + 164 (GSEvent.c:2196) 21 UIKitCore 0x19218ada0 -[UIApplication _run] + 816 (UIApplication.m:3789) 22 UIKitCore 0x19223917c UIApplicationMain + 340 (UIApplication.m:5439) 23 xxxxx 0x102c1d7b4 main + 84 (main.m:34) 24 dyld 0x1b5120d34 start + 2724 (dyldMain.cpp:1334) Thread 0 name: Thread 0 Crashed: 0 libsystem_kernel.dylib 0x00000001df6be254 __pthread_kill + 8 (:-1) 1 libsystem_pthread.dylib 0x0000000216999ef8 pthread_kill + 268 (pthread.c:1721) 2 libsystem_c.dylib 0x0000000197367ad8 abort + 128 (abort.c:122) 3 libc++abi.dylib 0x00000002168bd5b8 abort_message + 132 (abort_message.cpp:78) 4 libc++abi.dylib 0x00000002168abbac demangling_terminate_handler() + 348 (cxa_default_handlers.cpp:77) 5 libobjc.A.dylib 0x000000018c97ee04 _objc_terminate() + 156 (objc-exception.mm:496) 6 qihooloan_ios 0x000000010397a790 CPPExceptionTerminate() + 504 7 libc++abi.dylib 0x00000002168bc87c std::__terminate(void (*)()) + 16 (cxa_handlers.cpp:59) 8 libc++abi.dylib 0x00000002168c00ac __cxa_rethrow + 204 (cxa_exception.cpp:648) 9 libobjc.A.dylib 0x000000018c97a650 objc_exception_rethrow + 44 (objc-exception.mm:399) 10 CoreFoundation 0x000000018f62b67c CFRunLoopRunSpecific + 768 (CFRunLoop.c:3430) 11 GraphicsServices 0x00000001db3331c4 GSEventRunModal + 164 (GSEvent.c:2196) 12 UIKitCore 0x000000019218ada0 -[UIApplication _run] + 816 (UIApplication.m:3789) 13 UIKitCore 0x000000019223917c UIApplicationMain + 340 (UIApplication.m:5439) 14 xxxxx 0x0000000102c1d7b4 main + 84 (main.m:34) 15 dyld 0x00000001b5120d34 start + 2724 (dyldMain.cpp:1334)
4
1
1k
Aug ’24
Date.FormatStyle.Symbol.Hour defaultDigits shows leading zero if amPM is set to .omitted
I'm trying to format a date to show the current time with the least amount of digits as possible. Using Date.FormatStyle and adding .hour() is the closest I can get. See the code below ↓ var formatStyle = Date.FormatStyle() var hourMinute: Date.FormatStyle{ formatStyle .hour() .minute() } // Output 3:15 PM var hourMinuteDefaultDigits: Date.FormatStyle{ formatStyle .hour(.defaultDigits(amPM: .omitted)) .minute() } // Output 03:15 My goal is to output 3:15 without the amPm but that doesn't seem possible using Date.FormatStyle. Based on the documentation this is the function signature func hour(_ format: Date.FormatStyle.Symbol.Hour = .defaultDigits(amPM: .abbreviated)) -> Date.FormatStyle // Output 3:15 PM For some reason if I put .omitted for the amPM then defaultDigits and twoDigits return the same 2 digits for the hour
1
0
300
Aug ’24
Typedef redefinition of ULONG between iODBC Framework and CFPluginCOM.h
I've been using the iODBC framework (https://sourceforge.net/projects/iodbc/files/iodbc/3.52.16/iODBC-SDK-3.52.16-macOS11.dmg/download) for some time in a few Xcode Objective-C projects. Older projects work. Recent new projects fail to compile, with the following error: /Library/Frameworks/iODBC.framework/Headers/sqltypes.h:220:24 Typedef redefinition with different types ('unsigned long' vs 'UInt32' (aka 'unsigned int')) The definition in question, from iODBC/sqltypes.h, is: typedef unsigned long ULONG; The previous definition, from CoreFoundation/CFPluginCOM.h is: typedef UInt32 ULONG; Older projects open, compile and run normally in Xcode 15 and earlier. Only new projects created with Xcode 14 or 15 exhibit this behavior. CoreFondation/CFPluginCOM.h appears to provide non-essential Component Object Model (COM) support for Win32 apps. The definition of ULONG as UInt32 looks odd considering that CFPluginCOM seems to be aimed at 32-bit architecture. I find no way to mitigate this conflict within the Xcode project. Is there some way to exclude CFPluginCOM.h, which appears non-essential, from my project?
1
0
269
Aug ’24
iPadOS Calculator APIs for Developers
I'm working on an application where users can create their own equations using different math functions, like, sqrt, log, pow, exp, etc. and app calculates them with the provided values and displays the result. User also has the option to select the number of digits they want to round the result to. I'm using 'Double' data type and having precision issues with some of the equation results. Below are some examples: Example1: let a = 0.2 let b = 0.1 let result = a + b print(result) Printed result: 0.30000000000000004 Expected result: 0.3 Example2: let a = 9.495 let b = 0.2 let result = a + b print(result) Printed result: 9.694999999999999 Expected result: 9.695 Once they calculate the equation there is a requirement to match the result with the provided text. Which in the above cases fails. One of the solutions is to use the “Decimal” data type, but math functions like square root and log are not available for the Decimal data type. Please let me know if there is any way to resolve these issues by continuing to use “Double”. Or please help in writing a custom implementation for all math functions for ‘Decimal’, or could you inform us if Apple has any plans to make the calculator Apis available for developers? Thanks in Advance.
1
0
291
Aug ’24
Does objc_setAssociatedObject() work reliably when used with "bridgeable" Core Foundation types?
I'm investigating an odd problem that surfaced with macOS Sequoia related to CoreGraphics (CGColorSpaceCreateWithICCData()). I couldn't find a reliable way to track the lifetime (retain/releases) of a CGColorSpaceRef (any pointers appreciated) so I was hoping to use objc_setAssociatedObject() to attach an instance of my own class that would be deallocated when the "owning" CGColorSpaceRef is deallocated. In this way I could set a breakpoint on my own code, presumably invoked when the CGColorSpaceRef is itself going away. While objc_setAssociatedObject() does seem to work, the results don't seem deterministic. Is it because objc_setAssociatedObject() simply won't work reliably with CF types?
6
0
611
Aug ’24
get image icon of running applications in daemon
I need to get image icon of running applications in daemon. I have found the method iconForFile. [[NSWorkspace sharedWorkspace] iconForFile: bundlePath]; However, as far as I know, the framework AppKit is not daemon-safe. https://developer.apple.com/library/archive/technotes/tn2083/_index.html So, the only way which I see is to get icon file path via parsing Info.plist. However, the icon is not defined for some system app, e.g.: /System/Applications/Calendar.app /System/Applications/System Settings.app Are there any way to get icons of system application in daemon code? Is it safe to use NSBundle in daemon code? Thank you in advance.
2
0
465
Aug ’24
WeatherKit :: DailyForecast :: Sunrise :: ForEach :: Timezone Issue
My application engages the following: Generates and properly displays a selected location with MapKit. Generates SwiftUI WeatherKit information for a selected MapKit location. Generates correct Timezone WeatherKit [DayWeather] Sunrise and Sunset times within my timezone using the [ForEach] function. Generates incorrect Timezone WeatherKit [DayWeather] using the ForEach function, while retrieving Sunrise and Sunset times outside of my timezone. I modified my MapKit application to locate and retrieve weather information at specified locations. The application correctly illustrates all the weather information views I want to display without issue for a MapKit selected location. One view exception presents itself specific to the [ForEach] function inside a WeatherKit view, which retrieves Sunrise and Sunset information. The retrieved Sunrise and Sunset times for a selected timezone location outside of my identified timezone are not correct. My application does not generate nor apply an incorrect timezone identifier, such as [Europe/Paris] anywhere within the application, but the following view code segment surely hiccups. The selected timezone location view presents the Sunrise and Sunset time information as an equivalent time within my timezone, displayed in the images below. The issue happens to be within the view's following ForEach function code: Text(day.sun.sunrise?.formatted(.dateTime.hour().minute()) ?? "?") For the moment, I am struggling to discover how to correct the above code to properly display the [Sunrise] and [Sunset] times within a [ForEach] function. I do not know whether this issue happens to be inherent to WeatherKit's ForEach function, but most likely I am not properly applying the code to reflect the selected location's timezone format within the [Text]. I have not found a solution to apply within the [ForEach] function to correct this issue, as the application iterates through the supplied WeatherKit DayWeather information. I know I can retrieve the correct current TimeZone time for a selected location with the following code: func main() { let d = Date() // Show the [VARIABLE f] as [HOUR / MINUTE] such as [12:23PM] var f = Date.FormatStyle.dateTime.hour().minute() print("The [LOCAL TIME ZONE TIME with MAIN] :: \(d.formatted(f))") f.timeZone = TimeZone(identifier: "Europe/Paris")! print("The [SELECTED TIME ZONE TIME with MAIN] :: \(d.formatted(f))\n") } // Call the function main() The above code does not solve my application's issue, because the code simply returns the selected location's current timezone time relative to my current timezone time. So, if my timezone time happens to be 1:40 PM, then the above code generates a timezone time for a selected location, such as Paris to be 9:40 PM. I know a [View] does not respond to the incremental function code, such as stated above. As a side note :: My application displays the WeatherKit information through a Container and Hosting Controller, where the application's SwiftUI ContentView calls :: if let dailyForecast { TestForecastView(dailyForecast: dailyForecast, timezone: timezone) } If you have a moment, I appreciate your possible corrective suggestions, which would be very welcome ... :] Best regards, jim_k My TestForecastView Code with the attached generated views follow: import Foundation import SwiftUI import CoreLocation import WeatherKit struct TestForecastView: View { let dailyForecast: Forecast&lt;DayWeather&gt; let timezone: TimeZone var body: some View { Spacer() .frame(height: 10) Text("Sunrise Sunset") .font(.system(size: 24, weight: .bold)) .foregroundStyle(.white) Text("Ten Day Forecast") .font(.system(size: 11, weight: .medium)) .foregroundStyle(.white) Spacer() .frame(height: 4) VStack { ForEach(dailyForecast, id: \.date) { day in LabeledContent { HStack(spacing: 20) { RoundedRectangle(cornerRadius: 10) .fill(Color.orange.opacity(0.5)) .frame(width: 120, height: 5) .padding(.leading, 2) .padding(.trailing, 0) VStack { Image(systemName: "sunrise") .font(.system(size: 24.0, weight: .bold)) .foregroundColor(.yellow) Text(day.sun.sunrise?.formatted(.dateTime.hour().minute()) ?? "?") .font(.system(size: 10.0)) } .frame(width: 50, height: 20) VStack { Image(systemName: "sunset") .font(.system(size: 24.0, weight: .bold)) .foregroundColor(.yellow) Text(day.sun.sunset?.formatted(.dateTime.hour().minute()) ?? "?") .font(.system(size: 10.0)) } .frame(width: 50, height: 20) Spacer() .frame(width: 2) } } label: { Text(day.date.localDate(for: timezone)) .frame(width: 80, alignment: .leading) .padding(.leading, 30) .padding(.trailing, 0) } .frame(width: 380, height: 52) .background(RoundedRectangle(cornerRadius: 4).fill(LinearGradient(gradient: Gradient(colors: [Color(.systemBlue), Color(.black)]), startPoint: .topLeading, endPoint: .bottomTrailing)).stroke(.black, lineWidth: 6).multilineTextAlignment(.center)) .shadow(color: Color.white.opacity(0.1), radius: 4, x: -2, y: -2) .shadow(color: Color.white.opacity(0.1), radius: 4, x: 2, y: 2) } } .padding(.top, 20) .padding(.bottom, 20) .padding(.leading, 20) .padding(.trailing, 20) .contentMargins(.all, 4, for: .scrollContent) .background(RoundedRectangle(cornerRadius: 10).fill(Color.black.opacity(0.0)).stroke(.gray, lineWidth: 4)) } // End of [var body: some View] } // End of [struct TestForecastView: View] My resultant code views :: Calgary Paris
4
0
491
Aug ’24
/System/Library/Frameworks dylibs are ... not quite there
While playing with this app I found something odd: let dylib1 = dlopen("/System/Library/Frameworks/CreateMLComponents.framework/CreateMLComponents", O_RDONLY)! let s1 = dlsym(dylib1, "CreateMLComponentsVersionString")! var info1 = Dl_info() let success1 = dladdr(s1, &info1) precondition(success1 != 0) print(String(cString: info1.dli_sname!)) // CreateMLComponentsVersionString let path1 = String(cString: info1.dli_fname!) print(path1) // /System/Library/Frameworks/CreateMLComponents.framework/Versions/A/CreateMLComponents let exists1 = FileManager.default.fileExists(atPath: path1) print(exists1) // true let dylib2 = dlopen("/System/Library/Frameworks/Foundation.framework/Foundation", O_RDONLY)! let s2 = dlsym(dylib2, "NSAllocateMemoryPages")! // var info2 = Dl_info() let success2 = dladdr(s2, &info2) precondition(success2 != 0) print(String(cString: info2.dli_sname!)) // NSAllocateMemoryPages let path2 = String(cString: info2.dli_fname!) print(path2) // /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation let exists2 = FileManager.default.fileExists(atPath: path2) print(exists2) // false The app runs fine and prints true for exists1 and false for exists2. That means that while both dlsym calls succeed and both dladdr calls return paths (within CreateMLComponents.framework and Foundation.framework correspondingly) the first file exists while the second file doesn't exist. This raises quite a few questions: Why some of the dylib files (in fact – most dylibs inside /System/Library/Frameworks hirerarchy) don't exist at the expected locations? Why do we have symbolic link files (like Foundation.framework/Foundation) that point to those non-existent locations? What is the purpose of those symbols links? Where are those missing dylib files in fact? They must be somewhere, no?! I guess to figure out the answer I could search the whole disk raw bytes for a particular byte pattern to know the answer but hope there's an easier way to know the truth! Why do we have some exceptional cases like "CreateMLComponents.framework" and a couple of others that don't follow the rules established by the rest? Thanks!
4
0
461
Aug ’24
Help Needed: Error Codes in VCPHumanPoseImageRequest.mm[85] and NSArrayM insertObject
Hey all 👋🏼 We're currently working on a video processing project using the Vision framework (face, body and hand pose detection), and We've encountered a couple of errors that I need help with. We are on Xcode 16 Beta 3, testing on an iPhone 14 Pro running iOS 18 beta. The error messages are as follows: [LOG_ERROR] /Library/Caches/com.apple.xbs/Sources/MediaAnalysis/VideoProcessing/VCPHumanPoseImageRequest.mm[85]: code 18,446,744,073,709,551,598 encountered an unexpected condition: *** -[__NSArrayM insertObject:atIndex:]: object cannot be nil What we've tried: Debugging: I’ve tried stepping through the code, but the errors occur before I can gather any meaningful insights. Searching Documentation: Looked through Apple’s developer documentation and forums but couldn’t find anything related to these specific error codes. Nil Check: Added checks to ensure objects are not nil before inserting them into arrays, but the error persists. Here are my questions: Has anyone encountered similar errors with the Vision framework, specifically related to VCPHumanPoseImageRequest and NSArray operations? Is there any known issue or bug in the version of the framework I might be using? Could it also be related to the beta? Are there any additional debug steps or logging mechanisms I can implement to narrow down the cause? Any suggestions on how to handle nil objects more effectively in this context? I would greatly appreciate any insights or suggestions you might have. Thank you in advance for your assistance! Thanks all!
3
0
623
Jul ’24
NumberFormat formatting exceeds 16 decimal places exception
Example1: let num = NSDecimalNumber(string: "0.123456789012345678909") let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.usesGroupingSeparator = true formatter.maximumFractionDigits = 25 formatter.minimumFractionDigits = 25 formatter.minimumIntegerDigits = 1 let str = formatter.string(from: num) ?? "" print(str) output "0.1234567890123460000000000" Example2: let num = NSDecimalNumber(string: "12323.123456789012345678909") let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.usesGroupingSeparator = true formatter.maximumFractionDigits = 25 formatter.minimumFractionDigits = 25 formatter.minimumIntegerDigits = 1 let str = formatter.string(from: num) ?? "" print(str) output "12,323.1234567890000000000000000" How to correctly format the contents of the above two inputs?
1
0
308
Jul ’24
What is the recommended way to count files recursively in a specific folder
Given a directory path (or NSURL) I need to get the total number of files/documents in that directory - recursively - as fast and light as possible. I don't need to list the files, and not filter them. All the APIs I found so far (NSFileManger, NSURL, NSDirectoryEnumerator) collect too much information, and those who are recursive - are aggregating the whole hierarchy before returning. If applied to large directory - this both implies a high CPU peak and slow action, and a huge memory impact - even if transient. My question: What API is best to use to accomplish this count, must I scan recursively the hierarchy? Is there a "lower level" API I could use that is below NSFileManager that provides better performance? One time in the middle-ages, I used old MacOS 8 (before MacOS X) file-system APIs that were immensely fast and allowed doing this without aggregating anything. I write my code in Objective-C, using latest Xcode and MacOS and of course ARC.
7
0
527
Jul ’24
Can't open file user granted access to.
Our app has a note section that allows you to drag and drop an email to it. Our app then adds a link to the note, that when clicked, will open the email again. Currently andy email dragged from the mail.app doesn't have a problem. Works fine. The issue is with other mail clients at least with Outlook. When a user drags and drops an email from Outlook, we add the link, and if you click the link it will open fine. The problem is that this only works as long as you don't close our app. If you close our app, re-open and click the Outlook email link, we get a permission error. The application “DragAndDropEmails” does not have permission to open “Re- Customize Login- Registration Form.eml.” “NSCocoaErrorDomain” - code: 256 “NSURL” : “file:///Applications/Microsoft%200utlook.app/” “NSLocalizedDescription” : “The application “Microsoft Outlook” could not be launched because a miscellaneous error occurred.” “NSUnderlyingError” : domain: “NSOSStatusErrorDomain” - code: 18446744073709551562 When a drop is made to the text view we check for an email drop like this: private func checkForEmailDrop(_ pasteboardItems: [NSPasteboardItem]?) -> Bool { for item in pasteboardItems ?? [] { for type in item.types { switch type.rawValue { // When using Apple Mail, the following type is returned. case "com.apple.mail.PasteboardTypeMessageTransfer": if let itemURL = item.string(forType: .URL) { if let url = URL(string: itemURL){ // Get the email subject. let subjectName = item.string(forType: .string) self.textStorage?.op1InsertMailMessageLink(withURL: url, subjectText: subjectName) return true } } // When using Outlook, the file promise type is returned and then we must also check to make sure the file is a .eml file (email file). case "com.apple.NSFilePromiseItemMetaData": if let itemFileURL = item.string(forType: .fileURL) { if let itemURL = URL(string: itemFileURL) { if itemURL.pathExtension == "eml" { // Get the email subject. let subjectName = itemURL.deletingPathExtension().lastPathComponent self.textStorage?.op1InsertMailMessageLink(withURL: itemURL, subjectText: subjectName) return true } } } default: break } } } return false } When the user clicks the link, we open it like this: let configuration = NSWorkspace.OpenConfiguration() let urlWithScheme = url.psoAddingSchemeIfNeeded() let appURLWithScheme = appURL.psoAddingSchemeIfNeeded() print(urlWithScheme) print(appURLWithScheme) NSWorkspace.shared.open([urlWithScheme], withApplicationAt: appURLWithScheme, configuration: configuration) { app, error in if let error = error { print("Failed to open link in specific app: \(error.localizedDescription)") } } contents of urlWithScheme: "file:///Users/joseines/Library/Containers/com.microsoft.Outlook/Data/tmp/FB810D5A-D544-46D9-9BD0-65067A3D7DE4/Re-%20Customize%20Login-%20Registration%20Form.eml" contents of appURLWithScheme: file:///Applications/Microsoft%20Outlook.app/ How can we let the system know that the user wants access to this file? How can we open the file after a restart?
1
0
284
Jul ’24
SwiftUI URLRequest Warning: "Connection has no local endpoint"
I have a simple SwiftUI application that sends a URLRequest as shown in the code snippet below: import SwiftUI @main struct GOGODemoApp: App { var body: some Scene { WindowGroup { MyView() } } } struct MyView: View { var body: some View { Button("Click") { sendHTTPRequest(to: "https://www.google.com") { code, err in print("Finished, code: \(code ?? -1), err: \(String(describing: err))") } } } } func sendHTTPRequest(to urlString: String, completion: @escaping (Int?, Error?) -&gt; Void) { guard let url = URL(string: urlString) else { completion(nil, NSError(domain: "InvalidURL", code: 0, userInfo: nil)) return } let task = URLSession.shared.dataTask(with: url) { _, resp, error in if let httpResponse = resp as? HTTPURLResponse { completion(httpResponse.statusCode, error) } else { completion(-1, error) } } task.resume() } However, Xcode prints the following warning messages: nw_connection_copy_connected_local_endpoint_block_invoke [C1] Connection has no local endpoint nw_connection_copy_connected_local_endpoint_block_invoke [C1] Connection has no local endpoint nw_connection_copy_connected_local_endpoint_block_invoke [C3] Connection has no local endpoint nw_connection_copy_connected_local_endpoint_block_invoke [C3] Connection has no local endpoint Finished, code: 200, err: nil What does the warning 'Connection has no local endpoint' mean? Thank you for your assistance!
1
0
856
Jul ’24
iOS18 beta API
When the usesGroupingSeparator is set to yes on iOS18, the groupingSize value becomes 3. groupingSize is different from 0 in earlier iOS18 versions. Is it a bug or will the subsequent official version also make relevant adjustments? We need to adapt the app in advance。 let formatter = NumberFormatter() let temp = NSNumber(floatLiteral: value) formatter.usesGroupingSeparator = true; print(formatter.string(from: temp) ?? "","--",formatter.groupingSize) Print results below: iOS18 2222222 -- 0 earlier iOS18 2,222,222 -- 3
1
0
594
Jul ’24
iOS 18 beta 版本API
iOS18 beta版本,usesGroupingSeparator设置为yes后,groupingSize值变成了3.与iOS18以下groupingSize值为0不一样。是bug还是后续正式版本也做相关调整? let formatter = NumberFormatter() let temp = NSNumber(floatLiteral: value) formatter.usesGroupingSeparator = true; print(formatter.string(from: temp) ?? "","分割位数",formatter.groupingSize) //iOS18以下打印结果:2222222 分割位数 0;iOS18打印结果:2,222,222 分割位数 3
1
0
420
Jul ’24
iOS18 usesGroupingSeparator设置为yes后,groupingSize值变成了3.与iOS18以下groupingSize值为0不一样。是bug还是后续正式版本也做相关调整?需要提前适配
iOS18 beta版本,usesGroupingSeparator设置为yes后,groupingSize值变成了3.与iOS18以下groupingSize值为0不一样。是bug还是后续正式版本也做相关调整? let formatter = NumberFormatter() let temp = NSNumber(floatLiteral: value) formatter.usesGroupingSeparator = true; print(formatter.string(from: temp) ?? "","分割位数",formatter.groupingSize) //iOS18以下打印结果:2222222 分割位数 0;iOS18打印结果:2,222,222 分割位数 3
1
0
364
Jul ’24
Received termination request from [osservice<com.apple.dasd>:76] on <RBSProcessPredicate <RBSProcessHandlePredicateImpl| app<com.myapp.bundleid() with context <RBSTerminateContext| explanation:BG Kill Demo
App getting terminated as the app enters background state. No crash logs are generated. I have collected this log from Console(Mac app)by connecting iPhone and sending my app to background. There is no meaningful reason or code I can get from the logs. Can you please help me with what does 'explanation:BG Kill Demo ' means ? My app is a VoIP app. App depends on voip apns notifications to receive information about new Voip calls from server. I am posting the logs collected from console app here. default 14:29:55.265590-0400 audiomxd -CMSessionMgr- CMSessionMgrHandleApplicationStateChange: Sending stop command to com.myapp.bundleid with pid '2933' because client is background suspended and there is no AirPlay video session for it default 14:29:55.265753-0400 dasd Received state update for 2933 (app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>, running-suspended-NotVisible default 14:29:55.265908-0400 locationd Received state update for 2933 (app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>, running-suspended-NotVisible default 14:29:55.265994-0400 locationd {"msg":"invoking applicationStateChange handler", "StateChangeData":"{\n BKSApplicationStateAppIsFrontmost = 0;\n BKSApplicationStateExtensionKey = 0;\n SBApplicationStateDisplayIDKey = "com.myapp.bundleid";\n SBApplicationStateKey = 2;\n SBApplicationStateProcessIDKey = 2933;\n SBMostElevatedStateForProcessID = 2;\n}"} default 14:29:55.266083-0400 locationd {"msg":"Post Application State Change Notification", "notification":"BackgroundTaskSuspended", "pid":2933, "bundleId":"com.myapp.bundleid"} default 14:29:55.267019-0400 locationd {"msg":"#CLIUA AppMonitor notification", "notification":"BackgroundTaskSuspended", "pid":2933, "bundleId":"com.myapp.bundleid", "ClientKey":"icom.myapp.bundleid:"} default 14:29:55.267061-0400 locationd {"msg":"skip erasing #CLIUA for RunningBoard Process State. Does not exists", "bundleId":"com.myapp.bundleid"} default 14:29:55.267678-0400 watchdogd Received state update for 2933 (app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>, running-suspended-NotVisible default 14:29:55.267765-0400 useractivityd Received state update for 2933 (app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>, running-suspended-NotVisible default 14:29:55.267934-0400 symptomsd Received state update for 2933 (app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>, running-suspended-NotVisible default 14:29:55.267982-0400 wifid Received state update for 2933 (app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>, running-suspended-NotVisible default 14:29:55.268228-0400 UserEventAgent Received state update for 2933 (app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>, running-suspended-NotVisible default 14:29:55.268275-0400 callservicesd Received state update for 2933 (app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>, running-suspended-NotVisible default 14:29:55.268338-0400 WirelessRadioManagerd Received state update for 2933 (app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>, running-suspended-NotVisible default 14:29:55.269217-0400 runningboardd Acquiring assertion targeting [app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>:2933] from originator [osservice<com.apple.dasd>:76] with description <RBSAssertionDescriptor| "DAS: Application is docked." ID:33-76-44901 target:2933 attributes:[ <RBSDomainAttribute| domain:"com.apple.dasd" name:"DockApp" sourceEnvironment:"(null)"> ]> default 14:29:55.269572-0400 runningboardd Assertion 33-76-44901 (target:[app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>:2933]) will be created as active default 14:29:55.270431-0400 runningboardd [app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>:2933] Set jetsam priority to 30 [0] flag[1] default 14:29:55.270658-0400 runningboardd Calculated state for app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>: running-suspended (role: None) (endowments: (null)) default 14:29:55.273005-0400 runningboardd Received termination request from [osservice<com.apple.dasd>:76] on <RBSProcessPredicate <RBSProcessHandlePredicateImpl| app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>:2933>> with context <RBSTerminateContext| explanation:BG Kill Demo reportType:None maxTerminationResistance:Interactive> default 14:29:55.274715-0400 runningboardd Executing termination request for: <RBSProcessPredicate <RBSProcessHandlePredicateImpl| app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>:2933>> default 14:29:55.275034-0400 runningboardd [app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>:2933] Terminating with context: <RBSTerminateContext| explanation:BG Kill Demo reportType:None maxTerminationResistance:Interactive> default 14:29:55.275122-0400 runningboardd [app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>:2933] terminate_with_reason() success default 14:29:55.275768-0400 SpringBoard [app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>:2933] Workspace connection invalidated. default 14:29:55.275790-0400 SpringBoard [app<com.myapp.bundleid(AD9F24FF-321B-48U6-895F-723CDA943372)>:2933] Now flagged as pending exit for reason: workspace client connection invalidated default 14:29:55.275815-0400 backboardd Connection removed: IOHIDEventSystemConnection uuid:C2525EA6-A052-480B-B83D-4BD62C29C6EC pid:2933 process:MyApp type:Passive entitlements:0x0 caller:BackBoardServices: + 280 attributes:{ HighFrequency = 1; bundleID = "com.myapp.bundleid"; pid = 2933; } state:0x1 events:9 mask:0x800 dropped:0 dropStatus:0 droppedMask:0x0 lastDroppedTime:NONE default 14:29:55.275988-0400 backboardd Removing client connection <BKHIDClientConnection: 0xd43cd1f40; IOHIDEventSystemConnectionRef: 0xd415d5800; vpid: 2933(v1C3E); taskPort: 0x84D8B; bundleID: com.myapp.bundleid> for client: IOHIDEventSystemConnection uuid:C2525EA6-A052-480B-B83D-4BD62C29C6EC pid:2933 process:MyApp type:Passive entitlements:0x0 caller:BackBoardServices: + 280 attributes:{ HighFrequency = 1; bundleID = "com.myapp.bundleid"; pid = 2933; } state:0x1 events:9 mask:0x800 dropped:0 dropStatus:0 droppedMask:0x0 lastDroppedTime:NONE source:HID default 14:29:55.288098-0400 runningboardd [app<com.myapp.bundleid(AD9F24F321B-48U6C7-895F-723CDA943372)>:2933] termination reported by launchd (15, 0, 9) default 14:29:55.289192-0400 runningboardd Removing process: [app<com.myapp.bundleid(AD9F24F321B-48U6C7-895F-723CDA943372)>:2933] default 14:29:55.289331-0400 runningboardd Removing launch job for: [app<com.myapp.bundleid(AD9F24F321B-48U6C7-895F-723CDA943372)>:2933] default 14:29:55.289582-0400 runningboardd Removed job for [app<com.myapp.bundleid(AD9F24F321B-48U6C7-895F-723CDA943372)>:2933] default 14:29:55.289706-0400 runningboardd Removing assertions for terminated process: [app<com.myapp.bundleid(AD9F24F321B-48U6C7-895F-723CDA943372)>:2933]
3
0
655
Jul ’24
Unarchiving an object with custom classes
I have a custom class named CodeReadModel, which contains another custom class named CodeDataModel. The former contains the latter as an array like the following. class CodeReadModel: NSObject, NSSecureCoding { class var supportsSecureCoding: Bool { true } let identifier: String let codeDataModels: [CodeDataModel] init(identifier: String, codeDataModels: [CodeDataModel]) { self.identifier = identifier self.codeDataModels = codeDataModels } required init(coder decoder: NSCoder) { self.identifier = decoder.decodeObject(forKey: "identifier") as! String self.codeDataModels = decoder.decodeObject(forKey: "codeDataModels") as! [CodeDataModel] } func encode(with coder: NSCoder) { coder.encode(identifier, forKey: "identifier") coder.encode(codeDataModels, forKey: "codeDataModels") } } And I want to unarchive an object with the following. func importCodeReaderSnippetNext(fileURL: URL) { do { NSKeyedUnarchiver.setClass(CodeReadModel.self, forClassName: "CodeReadModel") NSKeyedUnarchiver.setClass(CodeDataModel.self, forClassName: "CodeDataModel") let data = try! Data(contentsOf: fileURL) if let codeReadModel = try NSKeyedUnarchiver.unarchivedObject(ofClass: CodeReadModel.self, from: data) { } } catch { print("Error: \(error.localizedDescription)") } } And I will get an error because codeReadModel contains another custom class, which cannot be decoded. How can I resolve this problem? Muchas thankos.
7
0
505
Jul ’24