Dive into the world of programming languages used for app development.

All subtopics

Post

Replies

Boosts

Views

Activity

Listening Changes Out of swiftUI in Observation Framework
Hi, folks. I know that in the new observation, class property changes can be automatically notified to SwiftUI, which is very convenient. But in the new observation framework, how to monitor the property changes of different model classes? For example, class1 has an instance of class2, and I need to notify class1 to perform some actions and make some changes when some properties of class2 are changed. How to do it in observation? In the past, I could use combined methods to write the second part of the code for monitoring. However, using the combined framework in observation is a bit confusing. I know this method can be withObservationTracking(_:onChange:) but it needs to be registered continuously. If Observation is not possible, do I need to change my design structure? Thanks. // Observation @Observable class Sample1 { var count: Int = 0 var name = "Sample1" } @Observable class Sample2 { var count: Int = 0 var name = "Sample2" var sample1: Sample1? init (sample1 : Sample1) { self.sample1 = sample1 } func render() { withObservationTracking { print("Accessing Sample1.count: \(sample1?.count ?? 0)") } onChange: { [weak self] in print("Sample1.count changed! Re-rendering Sample2.") self?.handleSample1CountChange() } } private func handleSample1CountChange() { print("Handling count change in Sample2...") self.count = sample1?.count ?? 0 } } // ObservableObject class Sample1: ObservableObject { @Published var count: Int = 0 var name = "Sample1" } class Sample2: ObservableObject { @Published var count: Int = 0 var name = "Sample1" var sample1: Sample1? private var cancellables = Set<AnyCancellable>() init (sample1 : Sample1) { self.sample1 = sample1 setupSubscribers() } private func setupSubscribers() { sample1?.$count .receive(on: DispatchQueue.main) .sink { [weak self] count in guard let self = self else { return } // Update key theory data self.count = count self.doSomeThing() } .store(in: &cancellables) } private func doSomeThing() { print("Count changes, need do some thing") } }
0
0
56
7h
Accessing AV External Storage
Is it possible to use the AVExternalStorageDevice to access external storage from a connected camera or usb drive (via USB C or Lightning connector) on an iPad/iPhone. I have tested the following code on an iPhone 14 (iOS 18.1.1) and an iPad Gen 10 (18.3.1), and both return false for: // returns false on iPhone 14, iPad gen 10 print(AVExternalStorageDeviceDiscoverySession.isSupported) The following code returns null, when I try to access the external storage discovery session. // returns null on iOS devices print(AVExternalStorageDeviceDiscoverySession.shared) The following returns false, without displaying a permission dialog: AVExternalStorageDevice.requestAccess(completionHandler: { (granted: Bool) in // returns false with no permission dialog print(granted); What type of iOS devices are supported by AVExternalStorageDeviceDiscoverySession? What situations has it been used for (e.g. connecting to Camera via the external storage protocol, accessing photos from a SD card with an adapter, accessing photos from usb drive). Is there are sample code for using the AV External Storage api?
0
0
85
10h
How to access comments and their associated text in iWork documents via AppleScript/ScriptingBridge?
Hi all, I’m developing a Mac OS application with XCode that interacts with iWork documents (Pages, Numbers, Keynote) using ScriptingBridge (and maybe AppleScript). Right now I started with Pages, assuming if it works for Pages, it will likely be similar for Numbers and Keynote. While I can successfully access and modify the main body text (e.g. the “body text” property in a Pages document), I’m having major difficulties accessing the comments (or annotations) within these documents. There are many aspects, but right now what I’m trying to achieve: For a Pages document, I need to scan the document and extract, for each comment: The content of the comment (i.e. the comment’s text). The text that is being commented on. For Numbers, similarly, I need to retrieve the commented cell’s content and the associated comment. For Keynote, the same as Pages, except I manage to get the Presenter Notes. Once done, I could replace the content accordingly. What I’ve tried: Using AppleScript commands such as: every comment of document "Test" Accessing properties like content or range of a comment. Attempting various syntaxes (including using class specifiers) to force AppleScript to recognize comments. Using ScriptingBridge in my Swift code, but I couldn’t find any mapping for a “comment” object in the Pages dictionary. However, all these attempts result in errors such as “cannot convert …” or “this class is not key value coding-compliant for the key …” which leads me to believe that the iWork scripting dictionaries may not expose comments (or annotations) in a scriptable way. Questions: Is there a supported way to access the comments (and the associated commented text) in an iWork document via AppleScript or ScriptingBridge? If so, what is the proper syntax or property name to use? (For example, should I be looking for a class named “comment”, “annotation”, or perhaps something else?) If direct access via AppleScript/ScriptingBridge is not possible, what alternative approaches would you recommend for programmatically extracting comment data from iWork documents? I apologize if my post isn't clear, it is translated from French. Any insights or examples would be greatly appreciated. Thank you!
0
0
75
20h
: Issue with App Group Preferences in iOS Message Extension
I’m encountering an issue while reading/writing shared preferences using UserDefaults with an App Group in my iOS Message Extension. The following error appears in the console: `Couldn't read values in CFPrefsPlistSource<0x3034e7f80> (Domain: [MyAppGroup], User: kCFPreferencesAnyUser, ByHost: Yes, Container: (null), Contents Need Refresh: Yes): Using kCFPreferencesAnyUser with a container is only allowed for System Containers, detaching from cfprefsd. I have correctly enabled the App Group in both my containing app and the Message Extension, and I am using UserDefaults(suiteName:) to access shared preferences. However, I keep getting this error when trying to read/write values. Has anyone encountered this before? How can I properly configure my app group preferences to avoid this issue? Any help would be greatly appreciated!
0
0
38
1d
Recover device enrolled email from any iOS device for an enterprise app?
Is the possibility of programmatically recovering the enrolled email address associated with an iPad. We are currently working on a project that requires us to retrieve this information for our enrolled devices. Could you please provide guidance or documentation on how we can achieve this programmatically? Specifically, we are interested in any APIs or frameworks that Apple provides for this purpose, as well as any necessary permissions or configurations that need to be in place.
0
0
31
1d
Dateformatter returns date in incorrect format
I have configured DateFormatter in the following way: let df = DateFormatter() df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" df.locale = .init(identifier: "en") df.timeZone = .init(secondsFromGMT: 0) in some user devices instead of ISO8601 style it returns date like 09/25/2024 12:00:34 Tried to change date format from settings, changed calendar and I think that checked everything that can cause the problem, but nothing helped to reproduce this issue, but actually this issue exists and consumers complain about not working date picker. Is there any information what can cause such problem? May be there is some bug in iOS itself?
1
0
148
5d
Swift 6 crash calling requestAutomaticPassPresentationSuppression
I found a similar problem here https://developer.apple.com/forums/thread/764777 and I could solve my problem by wrapping the call to requestAutomaticPassPresentationSuppression in a call to DispatchQueue.global().async. But my question is if this is really how things should work. Even with strict concurrency warnings in Swift 6 I don't get any warnings. Just a runtime crash. How are we supposed to find these problems? Couldn't the compiler assist with a warning/error. Why does the compiler make the assumptions it does about the method that is declared like this: @available(iOS 9.0, *) open class func requestAutomaticPassPresentationSuppression(responseHandler: @escaping (PKAutomaticPassPresentationSuppressionResult) -> Void) -> PKSuppressionRequestToken Now that we have migrated to Swift 6 our code base contains a bunch of unknown places where it will crash as above.
1
0
169
6d
CGSWindowShmemCreateWithPort log message
After ther Mac application is launched: Log error: CGSWindowShmemCreateWithPort failed on port 0 and when the application quit: No error handler for XPC error: Connection invalid Appear with Xcode 15.4 but not with 12.4 As repported by Steve4442 in "Can someone explain this message" https://Forums.Developer.Apple.com/Forums/Thread/727803 . The code don't use "windowNumbersWithOptions" Can I ignore this log message ?
10
0
233
1w
How do I locate and this Bundle Error
❌ Could not find email_ai.py in the app bundle. Available files: [] The error above is what I’m encountering. I’ve placed the referenced file both in the project directory and inside the app. However, every time I remove and reinsert the file into the folder within the app, it prompts me to designate the targets—I select all, but this doesn’t resolve the issue. I’m unsure how to properly reference the file so that it is recognised and included in the bundle. Any guidance would be greatly appreciated. this is my build phase: #!/bin/sh set -x # Prints each command before running it (for debugging) pwd # Shows the current working directory echo "$SRCROOT" # Shows what Xcode thinks is the project root ls -l "$SRCROOT/EmailAssistant/EmailAssistant/PythonScripts" # Lists files in the script folder export PYTHONPATH="/Users/caesar/.pyenv/versions/3.11.6/bin" /Users/caesar/.pyenv/versions/3.11.6/bin/python3 "$SRCROOT/EmailAssistant/EmailAssistant/PythonScripts/email_ai.py" echo "Script completed."
1
0
183
1w
Implementing RawRepresentable for a DictionaryType has broken my Test target build. Not sure how to fix things...
For my app I've created a Dictionary that I want to persist using AppStorage In order to be able to do this, I added RawRepresentable conformance for my specific type of Dictionary. (see code below) typealias ScriptPickers = [Language: Bool] extension ScriptPickers: @retroactive RawRepresentable where Key == Language, Value == Bool { public init?(rawValue: String) { guard let data = rawValue.data(using: .utf8), let result = try? JSONDecoder().decode(ScriptPickers.self, from: data) else { return nil } self = result } public var rawValue: String { guard let data = try? JSONEncoder().encode(self), // data is Data type let result = String(data: data, encoding: .utf8) // coerce NSData to String else { return "{}" // empty Dictionary represented as String } return result } } public enum Language: String, Codable, { case en = "en" case fr = "fr" case ja = "ja" case ko = "ko" case hr = "hr" case de = "de" } This all works fine in my app, however trying to run any tests, the build fails with the following: Conflicting conformance of 'Dictionary<Key, Value>' to protocol 'RawRepresentable'; there cannot be more than one conformance, even with different conditional bounds But then when I comment out my RawRepresentable implementation, I get the following error when attempting to run tests: Value of type 'ScriptPickers' (aka 'Dictionary<Language, Bool>') has no member 'rawValue' I hope Joseph Heller is out there somewhere chuckling at my predicament any/all ideas greatly appreciated
1
0
220
1w
Hash Collision in Data type
I notice that Swift Data type's hashValue collision when first 80 byte of data and data length are same because of the Implementation only use first 80 bytes to compute the hash. https://web.archive.org/web/20120605052030/https://opensource.apple.com/source/CF/CF-635.21/CFData.c also, even if hash collision on the situation like this, I can check data is really equal or not by == does there any reason for this implementation(only use 80 byte of data to make hashValue)? test code is under below let dataArray: [UInt8] = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] var dataArray1: [UInt8] = dataArray var dataArray2: [UInt8] = dataArray dataArray1.append(contentsOf: [0x00, 0x00, 0x00, 0x00]) dataArray2.append(contentsOf: [0xff, 0xff, 0xff, 0xff]) let data1 = Data(dataArray1) let data2 = Data(dataArray2) // Only last 4 byte differs print(data1.hashValue) print(data2.hashValue) print(data1.hashValue == data2.hashValue) // true print(data1 == data2) // false
1
0
247
1w
cell.textLabel?.text breaking if a number value is in an array
Hi the below array and code to output a list item works fine: var quotes = [ [ "quote": "I live you the more ...", "order": "1" ], [ "quote": "There is nothing permanent ...", "order": "2" ], [ "quote": "You cannot shake hands ...", "order": "3" ], [ "quote": "Lord, make me an instrument...", "order": "4" ] ] cell.textLabel?.text = quotes[indexPath.row]["quote"] However if I change the "order" values to be numbers rather than text like below then for the above line I get an error message in Xcode "No exact matches in call to subscript". Please could someone tell me how to make it work with the numbers stored as numbers? (I'm wondering if creating an any array type and using the .text function has caused a conflict but I can't find how to resolve) [ "quote": "I live you the more ...", "order": 1 ], [ "quote": "There is nothing permanent ...", "order": 2 ], [ "quote": "You cannot shake hands ...", "order": 3 ], [ "quote": "Lord, make me an instrument...", "order": 4 ] ] Thank you for any pointers :-)
2
0
207
1w
array.contains(where: ...) returns true in debugger console, but false in application
I am encountering a strange issue. I have a class that manages a selection of generic items T in an Array. It's a work in progress, but I'l try to give a gist of the setup. class FileManagerItemModel: NSObject, Identifiable, Codable, NSCopying, Transferable, NSItemProviderReading, NSItemProviderWriting { var id: URL static func == (lhs: FileManagerItemModel, rhs: FileManagerItemModel) -> Bool { lhs.fileURL == rhs.fileURL } var fileURL: URL { FileManagerItemModel.normalizedFileURL(type: type, rootURL: rootURL, filePath: filePath) } init(type: FileManagerItemType, rootURL: URL, fileURL: URL) { self.type = type self.rootURL = rootURL self.filePath = FileManagerItemModel.filePathRelativeToRootURL(fileURL: fileURL, rootURL: rootURL) ?? "[unknown]" self.id = FileManagerItemModel.normalizedFileURL(type: type, rootURL: rootURL, filePath: filePath) } } The class that manages the selection of these FileManagerItemModels is like so: @Observable class MultiSelectDragDropCoordinator<T: Hashable>: ObservableObject, CustomDebugStringConvertible { private(set) var multiSelectedItems: [T] = [] func addToSelection(_ item: T) { if !multiSelectedItems.contains(where: { $0 == item }) { multiSelectedItems.append(item) } } ... } My issue is that the check if !multiSelectedItems.contains(where: { $0 == item }) in func addToSelection fails. The if is always executed, even if multiSelectedItems contains the given item. Now, my first thought would be to suspect the static func == check. But that check works fine and does what it should do. Equality is defined by the whole fileURL. So, the if should have worked. And If I put a breakpoint in func addToSelection on the if, and type po multiSelectedItems.contains(where: { $0 == item }) in the debug console, it actually returns true if the item is in multiSelectedItems. And it properly return false if the item is not in multiSelectedItems. Still, if I then continue stepping through the app after the breakpoint was hit and I confirmed that the contains should return true, the app still goes into the if, and adds a duplicate item. I tried assigning to a variable, I tried using a function and returning the true/false. Nothing helps. Does anyone have an idea on why the debugger shows one (the correct and expected) thing but the actual code still does something different?
4
0
319
3w
Best way to learn Swift
Hi I'm new here - I'm trying to learn Swift and SwiftUI. Tried on PluralSight and Udemy but they have been outdated and thus hard to follow. So after finding Apples own guides I felt relieved and happy, but now I'm stuck again. After they've updated Xcode to use #Preview instead of PreviewProvider it's hard to follow along on their tutorial. Does anyone know of good resources to study SwiftUI? Or know if apple plan to update their tutorials any time soon? I'm here now if anyone's interested or it's useful information: https://developer.apple.com/tutorials/app-dev-training/managing-state-and-life-cycle
1
0
229
3w
Confusion About Objective-C's Memory Management (Cocoa)
Hello everyone, There is one thing about Objective-C's memory management that confuses me, which is a returned object's lifetime from methods with names doesn't start with "alloc", "new", "copy", or "mutableCopy". Take this as an example, when using NSBitmapImageRep's representationUsingType:properties: method, it returns an NSData object (reference: https://developer.apple.com/documentation/appkit/nsbitmapimagerep/representation(using:properties:)?language=objc). While testing this out, the NSData seemed to be an owned object (it doesn't get released until the end of the program). From what I understand, this may be an auto-released object which is released at the end of an autorelease pool block. Could someone explain this in more detail? What if I want to release that NSData object before the end of the autorelease pool block? How can I know which object is autoreleased, borrowed, or owned?
3
0
330
3w