Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

Package pre build script execution
Hello, i am currently trying to implement a pre build script execution in a package. I am using this tutorial to implement it. But it only shows how to use the pre build feature with an already existing feature. I want to execute a skript on my pc every time i build the project. I can't use apples prebuild skript feature in the build settings because it is a package. Right now my code looks like this: import Foundation import OSLog import PackagePlugin @main struct GenerateLocalizer: BuildToolPlugin {     do {       let commandlineOutput = try shell("./testScript.sh")     } catch {     }     return [.prebuildCommand(displayName: "Generate Strings", executable: PackagePlugin.Path("./scrips/generate_strings.sh"), arguments: [], outputFilesDirectory: target.directory)]   }   func shell(_ command: String) throws -> String {     let task = Process()     let pipe = Pipe()     task.standardOutput = pipe     task.standardError = pipe     task.arguments = [command]     os_log("%{public}@", log: log, task.arguments?.joined(separator: " ") ?? "not found")     task.launchPath = "/bin/zsh"     task.standardInput = nil     try task.run()     let data = pipe.fileHandleForReading.readDataToEndOfFile()     let output = String(data: data, encoding: .utf8)!     return output   } } and my Package file looks something like that       name: "CustomSdk",       dependencies: ["CustomSdk-Objc"],       path: "CustomSdk",       exclude: ["Info.plist", "CustomSdk.podspec"],       plugins: [         .plugin(name: "GenerateLocalizer")       ]     ),     .plugin(name: "GenerateLocalizer",         capability: .buildTool(),         dependencies: ["CustomSdk-Objc"]     ) It gets called properly but when want to write files in my "testScript.sh" it only says: Operation not permitted. Anyone got any ideas how to fix this or is there another way to utitlize custom scripts with custom packages? Greetings Ben
2
1
2.8k
Jun ’22
Calling Security Framework from Swift
I spend way too much time interacting with the Security framework. Most Security framework APIs are kinda clunky to call from Swift, largely because they use Core Foundation conventions. However, I see a lot of folks working much harder than they should to call these APIs. This post contains two tips to make your life easier. Many Security framework APIs work in terms of CFDictionary. I regularly see folks create these dictionaries like so: let query: [String: Any] = [ kSecClass as String: kSecClassKey, kSecMatchLimit as String: kSecMatchLimitAll, kSecReturnRef as String: true, ] var copyResult: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &copyResult) That’s much too hard. Try this instead: let query = [ kSecClass: kSecClassKey, kSecMatchLimit: kSecMatchLimitAll, kSecReturnRef: true, ] as NSDictionary var copyResult: CFTypeRef? let status = SecItemCopyMatching(query, &copyResult) Much nicer. Security framework APIs have a wide variety of ways to indicate an error: Some routines return an OSStatus and that’s it. Some routines return an OSStatus and an ‘out’ value. Some routines return a pointer, where nil indicates an error. Some routines return a pointer, where nil indicates an error, with a CFError ‘out’ value. Some routines return a Boolean, where false indicates an error, with a CFError ‘out’ value. In Swift you really just want to call the API and have it throw. The code pasted in at the end of this post helps with that. It declares a bunch of overloaded secCall(…) functions, one for each of the cases outlined above. It takes code like this: let query = [ kSecClass: kSecClassKey, kSecMatchLimit: kSecMatchLimitAll, kSecReturnRef: true, ] as NSDictionary var copyResult: CFTypeRef? = nil let err = SecItemCopyMatching(query, &copyResult) guard err == errSecSuccess else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(err)) } let keys = copyResult! as! [SecKey] and turns it into this: let query = [ kSecClass: kSecClassKey, kSecMatchLimit: kSecMatchLimitAll, kSecReturnRef: true, ] as NSDictionary let keys = try secCall { SecItemCopyMatching(query, $0) } as! [SecKey] Still not exactly pretty, but definitely an improvement. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Revision History 2023-11-27 Fixed a polarity bug with the Bool routine. As the saying goes “Real programmers can get the branch backwards in any language!” |-: /// Calls a Security framework function, throwing if it returns an error. /// /// For example, the `SecACLRemove` function has a signature like this: /// /// ``` /// func SecACLRemove(…) -> OSStatus /// ``` /// /// and so you call it like this: /// /// ``` /// try secCall { SecACLRemove(acl) } /// ``` /// /// - Parameter body: A function that returns an `OSStatus` value. /// - Throws: If `body` returns anything other than `errSecSuccess`. func secCall(_ body: () -> OSStatus) throws { let err = body() guard err == errSecSuccess else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(err), userInfo: nil) } } /// Calls a Security framework function that returns an error and a value indirectly. /// /// For example, the `SecItemCopyMatching` function has a signature like this: /// /// ``` /// func SecItemCopyMatching(…, _ result: UnsafeMutablePointer<CFTypeRef?>?) -> OSStatus /// ``` /// /// and so you call it like this: /// /// ``` /// let keys = try secCall { SecItemCopyMatching([ /// kSecClass: kSecClassKey, /// kSecMatchLimit: kSecMatchLimitAll, /// kSecReturnRef: true, /// ] as NSDictionary, $0) } /// ``` /// /// - Parameter body: A function that returns an `OSStatus` value and takes a /// ‘out’ pointer to return the result indirectly. /// - Throws: If `body` returns anything other than `errSecSuccess`. /// - Returns: The value returned indirectly by the function. func secCall<Result>(_ body: (_ resultPtr: UnsafeMutablePointer<Result?>) -> OSStatus) throws -> Result { var result: Result? = nil let err = body(&result) guard err == errSecSuccess else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(err), userInfo: nil) } return result! } /// Calls a Security framework function that returns `nil` on error. /// /// For example, the `SecKeyCopyPublicKey` function has a signature like this: /// /// ``` /// func SecKeyCopyPublicKey(…) -> SecKey? /// ``` /// /// and so you call it like this: /// /// ``` /// let publicKey = try secCall { SecKeyCopyPublicKey(privateKey) } /// ``` /// /// - Parameters: /// - code: An `OSStatus` value to throw if there’s an error; defaults to `errSecParam`. /// - body: A function that returns a value, or `nil` if there’s an error. /// - Throws: If `body` returns `nil`. /// - Returns: On success, the non-`nil` value returned by `body`. func secCall<Result>(_ code: Int = Int(errSecParam), _ body: () -> Result?) throws -> Result { guard let result = body() else { throw NSError(domain: NSOSStatusErrorDomain, code: code, userInfo: nil) } return result } /// Calls a Security framework function that returns `nil` on error along with a `CFError` indirectly. /// /// For example, the `SecKeyCreateDecryptedData` function has a signature like this: /// /// ``` /// func SecKeyCreateDecryptedData(…, _ error: UnsafeMutablePointer<Unmanaged<CFError>?>?) -> CFData? /// ``` /// /// and so you call it like this: /// /// ``` /// let plainText = try secCall { SecKeyCreateDecryptedData(privateKey, .rsaEncryptionPKCS1, cypherText, $0) } /// ``` /// /// - Parameter body: A function that returns a value, which returns `nil` if /// there’s an error and, in that case, places a `CFError` value in the ‘out’ parameter. /// - Throws: If `body` returns `nil`. /// - Returns: On success, the non-`nil` value returned by `body`. func secCall<Result>(_ body: (_ resultPtr: UnsafeMutablePointer<Unmanaged<CFError>?>) -> Result?) throws -> Result { var errorQ: Unmanaged<CFError>? = nil guard let result = body(&errorQ) else { throw errorQ!.takeRetainedValue() as Error } return result } /// Calls a Security framework function that returns false on error along with a `CFError` indirectly. /// /// For example, the `SecKeyVerifySignature` function has a signature like this: /// /// ``` /// func SecKeyVerifySignature(…, _ error: UnsafeMutablePointer<Unmanaged<CFError>?>?) -> Bool /// ``` /// /// and so you call it like this: /// /// ``` /// try secCall { SecKeyVerifySignature(publicKey, .ecdsaSignatureMessageX962SHA1, signedData, signature, $0) } /// ``` /// /// - Parameter body: A function that returns a false if there’s an error and, /// in that case, places a `CFError` value in the ‘out’ parameter. /// - Throws: If `body` returns false. func secCall(_ body: (_ resultPtr: UnsafeMutablePointer<Unmanaged<CFError>?>) -> Bool) throws { var errorQ: Unmanaged<CFError>? = nil guard body(&errorQ) else { throw errorQ!.takeRetainedValue() as Error } }
0
0
2.6k
Jul ’22
Why use async/await vs completion handlers?
I'm pretty sure I'm missing something completely obvious, but I can't see what. I watched WWDC session, read the Swift evolution blog, and they all make sense, but still it doesn't click for me. Please help me out here :) . I'm diving into adopting the 'new' async/await style of coding (I know, it's old news at this point, but I could only get to it now), and so I'm all pumped to get my code to go eleven and therefore I wrote a small data-downloader class. It has one method, well two: one oldskool function with a completionHandler, and one new style async/await one. When using the oldskool one, it works as everyone would expect: print(1) dataFetcher.fetchSomeData { print(2) let data = $0 // process data ... print(3) } print(4) The output is, unsurprisingly: 1 4 2 3 Now, when I use my new style function: let data = await dataFetcher.fetchSomeData() // process data ... Xcode gives me an error: 'async' call in a function that does not support concurrency That makes sense, I am calling this in the viewDidLoad() method of a UIViewController subclass. Can't mark viewDidLoad() as await, as super's implementation is not async. No problem, let me wrap it in Task: print(1) Task { print(2) let data = await dataFetcher.fetchSomeData() // process data ... print(3) } print(4) No errors, and this code works exactly as expected, the output is: 1 4 2 3 So now I am wondering: why take the effort of changing/adding code for async/await style function that ultimately end up requiring exactly the same amount of code, and is exactly as non-linear as completionHandlers? Note that the dataFetcher only has one property, an instance ofURLSession, so I am also not even managing my own queues or threads in the oldskool method vs the new one. They just wrap URLSession's functions: func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask and func download(for request: URLRequest, delegate: URLSessionTaskDelegate? = nil) async throws -> (URL, URLResponse) Is async/await useful only with SwiftUI maybe? What am I missing here? Please help me see the light.
8
0
6.3k
Aug ’22
Swift Concurrency, Core Data, "partially thread-safe" types & Sendable conformance
Hi, Xcode warns me that NSPersistentContainer, NSManagedObjectContext, NSPersistentHistoryTransaction and NSPersistentHistoryToken are non-Sendable types and therefore cannot cross actor boundaries. These warnings occur even when I use @preconcurrency import CoreData (only works with Xcode 14.0 Beta, in Xcode 13.4.1, it says '@preconcurrency' attribute on module 'CoreData' is unused) I understand that types in Core Data have yet to be marked as Sendable when it makes sense. Although NSPersistentHistoryTransaction, and NSPersistentHistoryToken are reference types, they should qualify to be marked as Sendable in the future since these are immutable types, am I right? NSPersistentContainer provides variables and methods like viewContext and newBackgroundContext(). It would make sense that this type is thread-safe. However, I'm not sure about it, especially regarding its loadPersistentStores(completionHandler:) method. Is NSPersistentContainer (and its subclass NSPersistentCloudKitContainer) thread-safe and should it be marked as Sendable in the future? The case of and NSManagedObjectContext confuses me the most. Indeed, it has both thread-safe methods like perform(_:) and thread-unsafe methods like save(). Still, it should be possible to cross actor boundaries. Would such a "partially thread-safe" type quality to be marked as Sendable? If not, how can it cross actor boundaries? The reason I'm asking these questions is that I have a CoreDataStack type. It has mutable variables, such as var lastHistoryToken: NSPersistentHistoryToken?, needs to perform work without blocking the main thread, such as writing the token to a file, has async methods, uses notification observers, and needs to be marked as Sendable to be used by other controllers running on different actors. Since this type is related to back-end work, I made it an Actor. This type exposes the persistent container, and a method to create new background threads. However, I need to explicitly annotate all methods using await context.perform { ... } as nonisolated in this actor. Not doing so causes a data race to be detected at runtime. Is this a bug, and is making a Core Data stack an Actor the proper way to do it or is there a better solution? Any help would be greatly appreciated. Thanks. Xcode Configuration Xcode 13.4.1, Xcode 14.0 beta 5 The Xcode project is configured with Other Swift Flags set to -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks.
4
2
2.8k
Aug ’22
Error throws while using the speech recognition service in my app
Recently I updated to Xcode 14.0. I am building an iOS app to convert recorded audio into text. I got an exception while testing the application from the simulator(iOS 16.0). [SpeechFramework] -[SFSpeechRecognitionTask handleSpeechRecognitionDidFailWithError:]_block_invoke Ignoring subsequent recongition error: Error Domain=kAFAssistantErrorDomain Code=1101 "(null)" Error Domain=kAFAssistantErrorDomain Code=1107 "(null)" I have to know what does the error code means and why this error occurred.
19
3
8.9k
Sep ’22
UserDefaults not cleared after Uninstall
Hi, We assume that when uninstalling an application, the UserDefaults are deleted. Starting iOS16 we encounter complaints from clients that this is not the case. We have succeeded in debugging a device where this occurred (UserDefaults were not deleted after uninstall+install), but have not succeeded in recreating this issue on another device. We assume this issue has a connection to iCloud sync, although UserDefaults iCloud synching should be specifically set up (using NSUbiquitousKeyValueStore) which we have NOT set. Or maybe it has to do with Family Sharing. We are initializing the UserDefaults with suiteName for usage in widgets, but assume this has not connection to the bug.
6
0
5.2k
Oct ’22
Regex literals in Swift Packages
So far I'm unable to use Regex literals in my Swift Packages. Xcode simply gives a syntax error and has no idea I'm trying to do Regex. This is with Xcode 14.1 and all the platforms in the Package.swift have been set to the minimum requirement (iOS 16, macOS 13, etc) as well as the swift-tools-version set to 5.7. Using the Regex type directly (try Regex("[a-z]")) does work. It's just the literals that Xcode refuses to recognize. Regex literals do work in app projects and playgrounds. Is there a setting in the Package.swift or something I'm forgetting? Thanks in advance!
2
0
1.8k
Nov ’22
1 minute Delay in External Accessory framework showBluetoothAccessoryPicker
I have to pair the classic Bluetooth device with my iOS application. For that, I have implemented showBluetoothAccessoryPicker with the External Accessory framework. EAAccessoryManager.shared().showBluetoothAccessoryPicker(withNameFilter: nil)), this is the code I have used for that. Added "Supported external accessory protocols" in .plist and enabled Wireless Accessory Configuration from capabilities. The actual issue is the picker displaying the device to pair with a 1-minute delay. What is the reason behind this reason and how can we resolve that?
1
0
975
Nov ’22
How to use network sockets with async/await?
I have an application that communicates with custom external hardware on the network (using UDP). I have a thread that receives and process the UDP data and then signals a waiting thread by releasing a semaphore when data is available. A have a asyncSendAndReceive and asyncReceive function that just begs to use async/await. But I cannot simply switch because of the use of the semaphore. Various forums and discussions said that semaphores should no longer be used for signalling. If not semaphores, then what else? Note that my two async functions may not always block. If data was received before they were called, then it is queued (and the semaphore is signalled).
9
0
2.7k
Nov ’22
DriverKit | Memory limitations of AsyncCallback
We implemented communication between Swift App and DriverKit driver using IOConnectCallAsyncStructMethod. void USBDriverClass::registerAsyncCallback(){   // Async required variables   notificationPort = NULL;   machNotificationPort = NULL;   runLoopSource = NULL;       // Async initialization   globalRunLoop = CFRunLoopGetMain();   CFRetain(globalRunLoop);       notificationPort = IONotificationPortCreate(kIOMainPortDefault);   if (notificationPort == NULL)   {     printf("Failed to create notification port for application.\n");   }       machNotificationPort = IONotificationPortGetMachPort(notificationPort);   if (machNotificationPort == 0)   {     printf("Failed to get mach notification port for application.\n");   }       runLoopSource = IONotificationPortGetRunLoopSource(notificationPort);   if (runLoopSource == NULL)   {     printf("Failed to get run loop for application.\n");   }       // Establish our notifications in the run loop, so we can get callbacks.   CFRunLoopAddSource(globalRunLoop, runLoopSource, kCFRunLoopDefaultMode);       // Establish our "AsyncCallback" function as the function that will be called by our Dext when it calls its "AsyncCompletion" function.   // We'll use kIOAsyncCalloutFuncIndex and kIOAsyncCalloutRefconIndex to define the parameters for our async callback   // This is your callback function. Check the definition for more details.   asyncRef[kIOAsyncCalloutFuncIndex] = (io_user_reference_t)AsyncCallback;   // Use this for context on the return. For example you might pass "this". But since this example is entirely static, we'll skip that step.   asyncRef[kIOAsyncCalloutRefconIndex] = (io_user_reference_t)NULL;       kern_return_t ret = kIOReturnSuccess;   uint8_t words = 4;       size_t inputSize = sizeof(StructA);   StructA structA;       structA.tag = 1;   structA.length = 0;   structA.values[0] = 0x106000;   structA.values[1] = words * sizeof(uint32_t);       size_t outputSize = sizeof(OutputData);   OutputData data;   printf("registerAsyncCallback called");       ret = IOConnectCallAsyncStructMethod(connection, MessageType_RegisterAsyncCallback, machNotificationPort, asyncRef, kIOAsyncCalloutCount, &structA, inputSize, &data, &outputSize);   if (ret != kIOReturnSuccess)   {     printf("IOConnectCallAsyncStructMethod failed with error: 0x%08x.\n", ret);   } } And when we get data from device we send data back from Driver to Swift app ivars->mUSBProbeDriverClient->AsyncCompletion(ivars->streamingDataCallback, kIOReturnSuccess, asyncData, 16); Driver should transfer data to swift app asynchronously when it's provided by USB device so we can not transfer struct synchronously. Async call back has limitation of 16 of uint64_t only and our application require larger data transfer. The logical way to transfer data using a memory buffer and as per Apple documentation they are providing this using IODataQueueDispatchSource. But they have not provided any example or showed how to use this. How to use fill buffer and use it in swift app using IODataQueueDispatchSource?
1
1
1.2k
Nov ’22
Task not executing at all
I have an 8th generation iPad, now updated with iPadOS 16.2 (20C65) and I have an issue that I also saw on earlier 16.* betas. Task is not executing at all. This is so frustrating because I have adopted async/await in my app, I support iOS 15+, everything was working fine but now that stuff inside Task { } is not executed my app seems to be broken. (Note: my main device is an iPhone 11, still on iOS 16.0, and it works fine there.) It is also frustrating to see no other developers are complaining about this, like it happens only with my app. I have debugged with print statements and breakpoints and I can say for sure that stuff is not executing. Does anybody have any ideas? Anything else I can try? FB11866066
17
0
3.2k
Dec ’22
DeviceActivityMonitor - intervalDidStart() not able to restrict apps/categories/webCategories
I've followed along with the Screen Time API demos (https://developer.apple.com/videos/play/wwdc2021/10123/) Also followed along with this guide, which is essentially the same: https://www.folio3.com/mobile/blog/screentime-api-ios/ I'm able to restrict access to apps/categories with the FamilyActivityPicker and FamilyActivitySelection. I can set a DeviceActivitySchedule, and then use DeviceActivityCenter to start monitoring it. I can tell that the schedule is working, because MyMonitor:intervalDidStart() does get called, and it works except for the restricting of apps/categories/webCategories. It's as if MyModel does not have any values set from within MyMonitor. I've confirmed that MyModel does have the correct FamilyActivitySelection apps etc, everywhere else in my Target, before and after the MyMonitor:intervalDidStart() gets called. MyMonitor is in a separate target called MonitorExtension, that I created using the Device Activity Monitor Extension template. But I made sure to set the Target Membership of MyModel to both my main target, and my extension target. I have set NSExtensionPrincipalClass to $(PRODUCT_MODULE_NAME).MyMonitor, as suggested. I have added MyModel.swift to the Compiled Sources in my extensions Build Phases. I have edited my apps build scheme, to make sure the extension target is also built. One more interesting thing is that debugger breakpoints and print statements do not work from within my extension. I've even tried caching a string from within MyMonitor:intervalDidStart, and tried to retrieve it afterwards in my main target, but it is nil. Still, I've confirmed that intervalDidStart was actually called by adding any removing store.application.denyAppInstallation = true, and having it work correctly. I've spent so much time on this problem, any help would be massive.. Here are the files I've referenced: import UIKit import MobileCoreServices import ManagedSettings import DeviceActivity class MyMonitor: DeviceActivityMonitor {   let store = ManagedSettingsStore()   override func intervalDidStart(for activity: DeviceActivityName) {     super.intervalDidStart(for: activity)     let model = MyModel.shared     let applications = model.selectionToDiscourage.applicationTokens     let categories = model.selectionToDiscourage.categoryTokens     let webCategories = model.selectionToDiscourage.webDomainTokens          if applications.isEmpty {      print("No applications to restrict")     } else {      store.shield.applications = applications     }          if categories.isEmpty {      print("No categories to restrict")     } else {      store.shield.applicationCategories = ShieldSettings.ActivityCategoryPolicy.specific(categories, except: Set())     }          if webCategories.isEmpty {      print("No web categories to restrict")     } else {      store.shield.webDomains = webCategories     }     store.dateAndTime.requireAutomaticDateAndTime = true     store.account.lockAccounts = true     store.passcode.lockPasscode = true     store.siri.denySiri = true     store.appStore.denyInAppPurchases = true     store.appStore.maximumRating = 200     store.appStore.requirePasswordForPurchases = true     store.media.denyExplicitContent = true     store.gameCenter.denyMultiplayerGaming = true     store.media.denyMusicService = true     store.application.denyAppInstallation = true   }   override func intervalDidEnd(for activity: DeviceActivityName) {     super.intervalDidEnd(for: activity)     store.shield.applications = nil     store.shield.applicationCategories = nil     store.shield.webDomains = nil     store.dateAndTime.requireAutomaticDateAndTime = false     store.account.lockAccounts = false     store.passcode.lockPasscode = false     store.siri.denySiri = false     store.appStore.denyInAppPurchases = false     store.appStore.maximumRating = 1000     store.appStore.requirePasswordForPurchases = false     store.media.denyExplicitContent = false     store.gameCenter.denyMultiplayerGaming = false     store.media.denyMusicService = false     store.application.denyAppInstallation = false   } } import Foundation import FamilyControls import DeviceActivity import ManagedSettings class MyModel: ObservableObject {   static let shared = MyModel()   let store = ManagedSettingsStore()   private init() {}   var selectionToDiscourage = FamilyActivitySelection() {     willSet {       let applications = newValue.applicationTokens       let categories = newValue.categoryTokens       let webCategories = newValue.webDomainTokens       store.shield.applications = applications.isEmpty ? nil : applications       store.shield.applicationCategories = ShieldSettings.ActivityCategoryPolicy.specific(categories, except: Set())       store.shield.webDomains = webCategories      }   }   func initiateMonitoring(scheduleStart: DateComponents, scheduleEnd: DateComponents) {     let schedule = DeviceActivitySchedule(intervalStart: scheduleStart, intervalEnd: scheduleEnd, repeats: true, warningTime: nil)     print(scheduleStart)     print(scheduleEnd)     let center = DeviceActivityCenter()     do {       try center.startMonitoring(.daily, during: schedule)     }     catch {       print ("Could not start monitoring \(error)")     }          store.dateAndTime.requireAutomaticDateAndTime = false     store.account.lockAccounts = false     store.passcode.lockPasscode = false     store.siri.denySiri = false     store.appStore.denyInAppPurchases = false     store.appStore.maximumRating = 1000     store.appStore.requirePasswordForPurchases = false     store.media.denyExplicitContent = false     store.gameCenter.denyMultiplayerGaming = false     store.media.denyMusicService = false     store.application.denyAppInstallation = false   } } extension DeviceActivityName {   static let daily = Self("daily") } import SwiftUI import FamilyControls struct AppPicker: View {   @StateObject var model = MyModel.shared   @State var isPresented = false       var body: some View {     Button("Select Apps to Discourage") {       isPresented = true     }     .familyActivityPicker(isPresented: $isPresented, selection: $model.selectionToDiscourage)   } }
8
0
2.2k
Dec ’22
Does setAlternateIconName work in mac Catalyst?
I'm trying to change app icon on Dock in macOS from my app. But couldn't get to work. The setAlternateIconName works fine in iOS simulator, but when I run in on my mac (Catalyst) I got this error: The requested operation couldn’t be completed because the feature is not supported. Apple Doc - https://developer.apple.com/documentation/uikit/uiapplication/2806818-setalternateiconname Thank you
1
1
985
Dec ’22
WeatherKit Gives 404
When I'm using the following code into the simulator it gives the wanted result: Button {                 Task {                     localWeather = try await WeatherService.shared.weather(for: CLLocation(latitude: 52.5153, longitude: 6.08565), including:  .daily(startDate: Date(), endDate: Calendar.current.date(byAdding: .day, value: 1, to: Date())!)).first.debugDescription                 }             } label: {                 Text("Get the test weather")             }             Text(localWeather) When I'm using this exact code on a real device I get the following 404 error: [WeatherDataService] Received invalid http response code 404 for request: C7AEC7CC-E5F7-425D-8491-25B9302E2A0F:0 [WeatherService] Encountered an error when fetching weather data subset; location=<+52.51530000,+6.08565000> +/- 0.00m (speed -1.00 mps / course -1.00) @ 05/01/2023, 13:55:53 Central European Standard Time,  error=responseFailed(<NSHTTPURLResponse: 0x282ce0260> { URL: https://weather-data.apple.com/v3/weather/en/52.515/6.086?timezone=Europe/Amsterdam&dataSets=forecastHourly,forecastDaily&dailyStart=2023-01-10T12:00:00Z&dailyEnd=2023-01-10T12:00:00Z&hourlyStart=2023-01-10T11:00:00Z&hourlyEnd=2023-01-10T16:00:00Z&country=NL } { Status Code: 404, Headers {     "Access-Control-Allow-Origin" =     (         "*"     );     "Cache-Control" =     (         "max-age=0, no-cache, no-store"     );     Connection =     (         "keep-alive"     );     "Content-Length" =     (         0     );     "Content-Security-Policy" =     (         "default-src 'self';"     );     Date =     (         "Thu, 05 Jan 2023 12:59:27 GMT"     );     Expires =     (         "Thu, 05 Jan 2023 12:59:27 GMT"     );     Pragma =     (         "no-cache"     );     Server =     (         "AppleHttpServer/21be5247c6351682d1d9aa22fe98c8f0d4902838"     );     "Strict-Transport-Security" =     (         "max-age=31536000; includeSubDomains",         "max-age=31536000"     );     "X-Apple-Origin" =     (         "bcd49c7f-c567-3921-a041-3d4ef58e5423"     );     "X-B3-TraceId" =     (         c8c6547722afc53f     );     "X-Cache" =     (         "TCP_MISS from a104-110-190-91.deploy.akamaitechnologies.com (AkamaiGHost/10.10.3-45298580) (-)"     );     "X-Content-Type-Options" =     (         nosniff     );     "X-Frame-Options" =     (         DENY     );     "X-REQUEST-ID" =     (         "407e37bc-ddf6-45fd-84d0-1d3d3b8651b0"     );     "X-XSS-Protection" =     (         "1; mode=block"     ); } }, Optional("")) I fixed it once by deleting Xcode and the app from my iPhone, but that doesn't work anymore. Any suggestions?
3
3
1.5k
Jan ’23
AsyncPublisher of KeyValueObservingPublisher doesn't work
Hi, I'm trying to use async/await for KVO and it seems something is broken. For some reason, it doesn't go inside for in body when I'm changing the observed property. import Foundation import PlaygroundSupport class TestObj: NSObject {   @objc dynamic var count = 0 } let obj = TestObj() Task {   for await value in obj.publisher(for: \.count).values {     print(value)   } } Task.detached {   try? await Task.sleep(for: .microseconds(100))   obj.count += 1 } Task.detached {   try? await Task.sleep(for: .microseconds(200))   obj.count += 1 } PlaygroundPage.current.needsIndefiniteExecution = true Expected result: 0, 1, 2 Actual result: 0 Does anyone know what is wrong here?
2
1
2.3k
Jan ’23
How to import FBX SDK into my Swift project?
Hello everyone, I want to add FBX capabilities to my app so I downloaded and installed the FBX SDK for iOS from the Autodesk website. But when it came to setting up the sdk for my Xcode project, the only article I could find was from 2014 and the guide is outdated and doesn't work anymore. I do not know a lot about c or working with frameworks/APIs, so I need some help getting this set up... Thanks for any help in advance!
1
0
1.1k
Feb ’23
Unknown Insta-Crash With NO_CRASH_STACK
Hi! We've recently released an usual app-update, but suddenly got a bunch of crashes in App Store Connect and almost none in Firebase Crashlytics. According to customer support, for some users the app insta-crashes. A white screen appears for a flash and then they're returned to the home screen. The app always insta-crashes, only a reinstall fixes it. It makes sense while Crashlytics isn't reporting any crashes, because it doesn't even get a chance to run and upload the crash reports to their server. The Xcode organizer does show a bunch of crashes, but with no stack trace. It just says MyApp: NO_CRASH_STACK. Looking at the explicit 'xccrashpoint' in Finder reveals a couple of crash reports, that I've attached, but they're not that useful. As far as I can tell, the app crashes while it's trying to load the Swift core, that's embedded in the app, but I'm not sure why that would cause a crash. Maybe it was supposed to use the library embedded in iOS (/usr/lib/swift/libswiftCore.dylib)? Any help would be greatly appreciated 🍺! report.crash
3
0
1.5k
Mar ’23