Welcome to the Apple Developer Forums

Post your questions, exchange knowledge, and connect with fellow developers and Apple engineers on a variety of software development topics.

For questions about using Apple hardware and services, visit Apple Support Communities

Posts

Sort by:
Post not yet marked as solved
0 Replies
4 Views
I have a SwiftUI document based app where multiple documents can be open at the same time. I now want to have menu items in the main menu that send commands to the active window. Additionally, I want menu items to be disabled if no matching object is selected in the active window. As an example Finder can be used, where in the "Edit" menu the entries are different depending on the selected files. I tried using a class as shown below to communicate between the views and the Commands structure, which basically works. Unfortunately, this causes a command to arrive at all open documents. And if I have an entry selected in one window but not in another, the AppState object only reflects the last selected state. If I change the window, the app does not notice this for the time being. class AppState: ObservableObject { static let shared = AppState() @Published var dirEntryCommand = PassthroughSubject<DirCommand,Never>() @Published var selectedDirEntry: DirectoryEntry.ID? } The Commands struct looks like this: enum DirCommand: Int, Identifiable, CaseIterable { case rename case moveUp case moveDown var id: RawValue { rawValue } } struct DirEntryCommands: Commands { @ObservedObject var appState = AppState.shared var body: some Commands { CommandMenu("Directory Entry") { Section { Button("Move up") { appState.dirEntryCommand.send(.moveUp) } .keyboardShortcut("u") Button("Move down") { appState.dirEntryCommand.send(.moveDown) } .keyboardShortcut("d") } .disabled(appState.selectedDirEntry == nil) Section { Button("Rename…") { appState.dirEntryCommand.send(.rename) } .keyboardShortcut("r") } .disabled(appState.selectedDirEntry == nil) } } } It is possible that I am taking the wrong approach and that there is another solution to this problem. In a pure AppKit application I would implement the relevant commands in the ViewController and use the "magic" of the ResponderChain.
Posted
by
Post not yet marked as solved
2 Replies
15 Views
Hi all. I am not sure what is wrong with my current code. What I am looking to do is change all values of a string with a substring of "around #C" where # is the temperature. I am converting between farenheit and celsius and i wish to get all substrings then change the correct value depending on the current setting. So if i have a string where "This is today. The temperature is around 14C. Tomorrow the temperature will be around 18C" So the regex would get "around 14C" and "around 18C" and change the values to farenheit. Result would be something like "This is today. The temperature is around -1F. Tomorrow the temperature will be around -4F" This is my function. func formatCorrectDetail(_ detail: String, _ isCelsius: Bool) -> String {     let regex = try! NSRegularExpression(pattern: "around ((\\d+)" + (isCelsius ? "F" : "C") + ")", options: [])     let matches = regex.matches(in: detail, options: [], range: NSRange(location: 0, length: detail.utf16.count))     let formattedString = NSMutableString(string: detail)     for match in matches {       let range = match.range(at: 2)       if let rangeSubstring = Range(range, in: detail),         let temperature = Double(String(detail[rangeSubstring])) {         let val = isCelsius ? NumberTool.far2cel(temperature) : NumberTool.cel2far(temperature)         formattedString.replaceCharacters(in: range, with: val)       }     }     if formattedString.length > 0 {       return String(formattedString)     }     else {       return detail     }   } The NumberTool.far2cel() and NumberTool.cel2far() are my custom functions to convert between celsius and farehnheit. Thoughts?
Posted
by
Post not yet marked as solved
0 Replies
24 Views
Hi The company that I work for got rejected for Apple Developer Enterprise Program (When I asked, I was told no comment). Is someone able to explain how we can go about getting an app reviewed to be private in the app store without needing to provide login details? All user accounts are created on the company's Azure AD and providing a demo account is not an option as it would grant Apple too much access to confidential information plus in some cases, certain actions would send off notifications, and that may create unneeded panic in the company. Also access to some features are dependent on who you are in the company. Would doing a video help in this case or would the company not be welcomed at all? Cheers
Posted
by
Post not yet marked as solved
0 Replies
27 Views
This is probably a minor point because it wouldn't affect distributed binaries, but I thought I'd mention it in case the behavior is unexpected. After watching WWDC 20202 Explore logging in Swift, I tried some simple examples in a Mac command-line app. I was surprised to see the strings were all printed just fine. There was no redaction. At least when running the program from Xcode. (Even using the old os_log() approach showed the strings without needing to add %{public}@.) However, if I run the program from a Terminal shell, the string arguments are properly redacted. I actually like this behavior (showing more while running in Xcode), but I thought I'd just raise the issue. Sample code and screenshot from Console are shown below. import Foundation import os let logger = Logger(subsystem: "com.example.logging_test", category: "hello") let greeting = "Hello" let personName = "World" logger.log("\(greeting), \(personName)") logger.log("\(greeting, privacy: .private), \(personName)") logger.log("\(greeting, privacy: .public), \(personName)") os_log("%@, %@", greeting, personName)
Posted
by
Post not yet marked as solved
0 Replies
29 Views
Sometimes, a Mac gets stuck in secure keyboard input mode, which prevents event taps from working. Googling indicates that this is a perennial intermittent problem. I've seen the suggestion to find the responsible process by using the command line ioreg -l -w 0 | grep SecureInput and looking for a PID in the output. When this happened to me today, the PID was that of the loginwindow process. That seems to be a bogus "I don't really know" result. In my case, quitting Safari cleared the problem. But is there any better way to find out the real source of the problem than quitting apps one by one?
Posted
by
Post not yet marked as solved
0 Replies
24 Views
Hi, I have a P1 protocol, whose methods and properties are implemented by the C1 class. In NSViewController VC1, object OBJ1 of class C1 is instantiated. VC1 loads a new NSViewController VC2 through the segue, which needs access to the OBJ1 object. What is the best method to make VC2 see the object OBJ1, being able to modify it and return it to VC1? Thanks.
Posted
by
Post not yet marked as solved
0 Replies
30 Views
I'm trying to get results from a SQLite database, containing rows and columns, into a NSTableView, using Swift. There is no problem with the database query and I'm getting no errors when running the application. However, when displaying data, I always get the same (last) row in the table - repeated so many times as the total number of rows. What is missing in my code ? Thanks in advance. `class SecondViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate { @IBOutlet var tableview: NSTableView! var querySQL = "" var bdadosDB: OpaquePointer? var statement: OpaquePointer? var allRows = [String]() var rows = [String]() var cols = [String]() var CellIdentifiers :[String] = ["ordCell", "procCell", "espCell", "natCell", "recCell", "estCell", "julgCell", "decCell"] override func viewDidLoad() { let dirPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let docsDir = dirPaths[0] let databasePath = (docsDir as NSString).appendingPathComponent("bdados.db") let dbpath = databasePath sqlite3_open(dbpath, &bdadosDB) querySQL = "SELECT * FROM proc" sqlite3_prepare_v2(bdadosDB, querySQL, -1, &statement, nil) while (sqlite3_step(statement) == SQLITE_ROW) { let str = String(sqlite3_column_int(statement, 0)) + ";" let str_1 = String(cString: sqlite3_column_text(statement, 1)) + ";" let str_2 = String(cString: sqlite3_column_text(statement, 2)) + ";" let str_3 = String(cString: sqlite3_column_text(statement, 3)) + ";" let str_4 = String(cString: sqlite3_column_text(statement, 4)) + ";" let str_5 = String(cString: sqlite3_column_text(statement, 5)) + ";" let str_6 = String(cString: sqlite3_column_text(statement, 6)) + ";" let str_7 = String(cString: sqlite3_column_text(statement, 7)) let result = str + str_1 + str_2 + str_3 + str_4 + str_5 + str_6 + str_7 allRows.append(result) } let str_arr = allRows.joined(separator: "_") rows = str_arr.components(separatedBy: "_") tableview.dataSource = self tableview.delegate = self super.viewDidLoad() } func numberOfRows(in tableview: NSTableView) -> Int { return rows.count } func tableView(_ tableview: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { var text: String = "" var cellIdentifier: String = "" for i in 0 ..< rows.count { let rw = rows[i] cols = rw.components(separatedBy: ";") for j in 0 ..< cols.count { let col = cols[j] if tableColumn == tableview.tableColumns[j] { text = col cellIdentifier = CellIdentifiers[j] } } } if let cell = tableview.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier) , owner: nil) as? NSTableCellView { cell.textField?.stringValue = text return cell } else { return nil } } } `
Posted
by
Post not yet marked as solved
1 Replies
35 Views
I use Moho Studio on macOS to create an icon and a launch screen for my iOS application. But when I right click on the exported png file then I can see that the color profile is missing. I have tried to add this png file to Assets-->AppIcon image set in Xcode and I got no error message because the color profile is missing. My png file looks like this: Is it possible to use png files even if they don't have the color profile sRGB IEC61966-2.1? Is it possible that the images won't display correctly on an iOS device because the color profile is missing? I cannot add the color profile in Moho Studio. I would need another program if it is necessary to add the color profile to the png files. Which program should I use if I need to add the color profile to my Moho Studio png files?
Posted
by
Post not yet marked as solved
0 Replies
39 Views
I'm relatively new to Swift, and very new to concurrency via Async/Await, so please be patient. 😀 I'm having a hard time comprehending how to do complex operations asynchronously in background threads, and then in turn bring the results back to the main thread. I'm getting various errors along the lines of "Mutation of captured var 'personName' in concurrently-executing". I've paired the issue down as simply as possible as follows, and you'll see where the compiler gives the error message. I'd appreciate any advice on how to evolve my mental model to make this work. Thanks! Bruce import Foundation actor Person {     var myName = "Thomas Jefferson"     var name: String {         get {             return myName         }     } } func main() {     let person = Person()     var personName: String     print("start")     let nameTask = Task {         return await person.name     }     Task {         do {             personName = try await nameTask.result.get()             // Error: Mutation of captured var 'personName' in concurrently-executing code         } catch {             print("error!!!")         }     }     print("The person's name is \(personName)") } RunLoop.main.run() main()
Posted
by
Post not yet marked as solved
0 Replies
37 Views
Problem LongPressGesture ignores minimumDuration parameter and succeeds immediately, also onEnded is never invoked. Steps to reproduce Take Apple’s own sample code from their documentation: LongPressGesture. Remove transaction.animation = Animation.easeIn(duration: 2.0) line to make the effect more obvious. Expected result: The circle must turn red after 3 seconds of pressing on it, and turn green when released. Actual result The circle turns red immediately and never turns green. Notes I tried many combinations of .gesture and .simultaneousGesture applied to different types of views. Was anyone able to make the minimum duration work when passed to .gesture modifier?
Posted
by
Post not yet marked as solved
0 Replies
32 Views
NavigationStackView with .searchable modifier is working as expected. struct NavStackListSearchView: View { @State private var items = ["Item1", "Item2", "Item3", "Item4", "Item5"] @State private var selectedItems: Set<String> = [] @State private var searchText: String = "" var filteredItems: [String] { if searchText.isEmpty { return items } else { return items.filter { $0.contains(searchText) } } } var body: some View { NavigationStack { List(selection: $selectedItems) { ForEach(filteredItems, id: \.self) { item in NavigationLink(item) { Text(item).font(.title3) } } } } .searchable(text: $searchText) .onChange(of: searchText) { _ in selectedItems = [] } } } But NavigationSplitView with .searchable modifier is crashing: struct NavSplitListSearchView: View { @State private var items = ["Item1", "Item2", "Item3", "Item4", "Item5"] @State private var selectedItems: Set<String> = [] @State private var searchText: String = "" var filteredItems: [String] { if searchText.isEmpty { return items } else { return items.filter { $0.contains(searchText) } } } var body: some View { NavigationSplitView { List(selection: $selectedItems) { ForEach(filteredItems, id: \.self) { item in Text(item) } } } detail: { if selectedItems.isEmpty { Text("Pick an item") } else { Text("\(selectedItems.first ?? "--no item--")") } } .searchable(text: $searchText) .onChange(of: searchText) { _ in selectedItems = [] } } } To reproduce the crash in NavSplitView: launch the app click on "Item3" go back (if in compact mode) search for "3" click on only item shown, that is "Item3" --> crash Seems to be an issue with the index into the List/ForEach? But I see no way of influencing/double checking on that index. A change of filteredItems based on searchText should be recognised by SwiftUI as it is based on @State property items. What do I miss? How can I solve this issue? Target iOS 16.2, Xcode 14.2
Posted
by
Post not yet marked as solved
0 Replies
35 Views
This is very sad that a "Pro" device that is supposed to be 5G ready, only catches 4G signals in India despite network providers like jio/airtel providing 5g services. Considering the price point of the device iPad Pro, this is a very sad affair. Is there anyone who knows what's the issue and any solutions, if any?
Posted
by
Post not yet marked as solved
0 Replies
32 Views
Hey everyone, I want to release an app which has a subscription based premium version which can be bought via in-app purchases. Also, now I am selling licenses to Enterprise customers which then can use the premium version. What is the best way for them to redeem their license code, in order to be compliant with Apples Guidelines? I am thinking to build the function inside the app directly. Thanks for your help!
Posted
by
Post not yet marked as solved
0 Replies
42 Views
So, I'm trying to learn basics of Core Media since I need to process real time audio samples in my app. For now I know that I need to configure an AVCaptureSession setting an AVCaptureDevice used to acquire samples and an AVCaptureDataOutput that processes the input from the device and "notifies" an AVCaptureAudioDataSampleBufferDelegate through a captureOutput(...) method. Now, this one method gets passed the samples as an CMSampleBuffer object, that according to Apple's CM documentation, will contain zero or more media (audio in my case) samples and a CMBlockBuffer, that is [...] a CFType object that represents a contiguous range of data offsets [...] across a possibly noncontiguous memory region. OK So this is kinda getting confusing. I'm not a native speaker and I'm struggling to understand what this is supposed to mean. Why do I need this to access my samples? Aren't they stored as an array of raw binary data (therefore homogeneous and contiguous)? I guess this is related to how the underlying memory is managed by Core Media but I can't figure it out. Also the last batch of samples gets accessed through this CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer  method which expects an unsafe mutable pointer to an AudioBufferList and one to an optional CMBlockBuffer. The first one will be filled with pointers into the latter, and then I may (or may not) be able to access the samples through myAudioBufferList.mBuffers.mData, which might be nil. Example code from Apple Developers code snippets: public func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { var audioBufferList = AudioBufferList() var blockBuffer: CMBlockBuffer? CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer( sampleBuffer, bufferListSizeNeededOut: nil, bufferListOut: &audioBufferList, bufferListSize: MemoryLayout.stride(ofValue: audioBufferList), blockBufferAllocator: nil, blockBufferMemoryAllocator: nil, flags: kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, blockBufferOut: &blockBuffer) guard let data = audioBufferList.mBuffers.mData else { return } } What's the memory model (or pipeline) behind this? I truly appreciate any help.
Posted
by
Post not yet marked as solved
0 Replies
36 Views
I am facing an issue wherein I am unable to work with the project test files in Xcode. Whenever I try to scroll through or write a new line of code in any test file in the test target of a large project the IDE gets totally unresponsive and takes a lot of time to register a change. I have tried removing Xcode and reinstalling from app store and from apple website but the problem still persists. When I checked the cpu and memory usage, it shows Xcode using up all the cpu capacity. Any suggestions on how to resolve this? Please Note: I am using M1 MacBook Pro
Posted
by
Post not yet marked as solved
0 Replies
34 Views
Im trying to preview my model converted from gltf with reality converter, some of them work but some seem to be loading for 1 second and then crashes, im on ios 16.1.1
Posted
by
Post not yet marked as solved
0 Replies
39 Views
Hello everyone, In short, I was researching the usage of action sheets in the Shortcuts app and noticed that the UI did not match what I was seeing. Upon further investigation, I realized that it was not an action sheet. I have two questions regarding this issue. If anyone knows the name and purpose of the UI element shown in the images, please share that information. Additionally, if anyone has insights related to the two questions posed in the post, please share them. Thank you in advance. Questions: I would like to know which category this is from. This looks like an action sheet on the Apple Watch (Figure 1), but it has a different UI and slides down from the top to cover the view instead of sliding up from the bottom like a half-modal (Figure 2). When I change the view from grid to list, selecting the same option "What's a shortcut?" results in different amounts of information and selections(Figure 3). I don't understand why the view affects the differentiation. Figure 1 - Apple Watch Ultra V9 Up: Figure 2 - iPhone Screenshot1: Figure 3 - iPhone Screenshot2:
Posted
by
Post not yet marked as solved
4 Replies
39 Views
Not too hopeful that anyone can explain this but here is goes. I have some C code being used from an iOS app in Swift. Logs in the C code are passed by a callback to Swift and put on a serial queue using: Log.serialQueue.async {} So, the C function could look like: int do_some_c_stuff(void) { log("Do some logging"); } And in Swift we have something like this to process the log that came through the callback: class func log(_ message: String, logInfo: LogInfo = appLogInfo, type: OSLogType = .default) { Log.serialQueue.async { os.os_log("%@", log: logInfo.log, type: type, message) } } This works perfectly in all cases except one (Intel iPhone simulator only). Now, some C functions allocate a static buffer to parse incoming messages. Like this: int do_some_c_stuff(void) { log("Do some logging"); char buf[100000]; } and here is the interesting part. If this buffer exceeds exactly 249440 bytes, any call to Log.serialQueue.async in the swift layer gets a EXC_BAD_ACCESS code=2 but only when running on Intel simulator. Running on device or M1 simulator works just fine. So on the Intel simulator this will crash calling Log.serialQueue.async: int do_some_c_stuff(void) { log("Do some logging"); // This will trigger the callback inside log which ends up in the swift layer. char buf[249441]; // buffer exceeds 249440 bytes } Also note that it is the presence of this allocation that causes issues on Intel, returning before the allocation does not help, if the allocation is present in the C function, the call to Log.serialQueue.async crash. Further, it is not the logging in the swift layer that causes the problem, simply calling Log.serialQueue.async without anything inside crashes. So, the example below still crash on Intel when accessing the serialQueue.async so I assume the large memory chunk is allocated when the function is "created", not when the buf variable is instantiated. int do_some_c_stuff(void) { log("Do some logging"); return 0; char buf[249441]; } It only happens in the Intel simulator and only in Debug mode. It is 100% reproducible in various places in the codebase, all of them using C functions that declare a local buffer larger than 249440 bytes. I do not have a minimal example at this time, hoping that someone might have an idea on why it happens but if someone is interested, maybe I can whip something up. In general, just having the C function allocate this large block and from the same function callback to swift and use dispatch.async should do the trick. Is there some sort of memory swapping, paging etc that would cause problems in a scenario like this mixing C and dispatchqueue (on intel only)? Since the solution is to reduce the stack allocation or use heap memory, this is not critical. However, if anyone knows why this is happening on Intel CPU's it would be super interesting to know.
Posted
by
Post not yet marked as solved
0 Replies
37 Views
Our app collects idfa through this API. It's a simple computed property: var idfa: String { return ASIdentifierManager.shared().advertisingIdentifier.uuidString } But seems like it has a very low chance of crashing, based on our production record, it crashes 1 out of a million runs. The stack trace is: - 0 libswiftFoundation.dylib 0x0000000184c34728 0x184c1b000 + 104232 - XXXApp 0x000000010bd42d70 AdsDataCollector.idfa.getter + 156118384 (AdsDataCollector.swift:0) What could be the reason?
Posted
by

Pinned Posts

Categories

See all