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

All subtopics

Post

Replies

Boosts

Views

Activity

StoreKit Promotional Offer Purchase Failure - 'Unable to Purchase' Alert in Xcode
Hi everyone, I'm encountering an issue while testing a subscription purchase with a promotional offer using StoreKit in the Xcode debug environment. I’ve created a subscription in the StoreKit configuration file and added a promotional offer. However, when I attempt to make a purchase with the promotional offer, the process fails, and I receive an alert with the message: "Unable to purchase" "Contact the developer for more information." Here’s the error that is printed in the Xcode logs: Purchase did not return a transaction: Error Domain=ASDErrorDomain Code=3903 "Received failure in response from Xcode" UserInfo={NSDebugDescription=Received failure in response from Xcode, NSUnderlyingError=0x303346b50 {Error Domain=AMSErrorDomain Code=305 "Server Error" UserInfo={NSLocalizedDescription=Server Error, AMSServerErrorCode=3903, AMSServerPayload={ "cancel-purchase-batch" = 1; dialog = { defaultButton = ok; explanation = "Contact the developer for more information.\n\n[Environment: Xcode]"; initialCheckboxValue = 1; "m-allowed" = 0; message = "Unable to Purchase"; okButtonString = OK; }; dsid = 17322632127; failureType = 3903; jingleAction = inAppBuy; jingleDocType = inAppSuccess; pings = ( ); }, AMSURL=http://localhost:49300/WebObjects/MZBuy.woa/wa/inAppBuy, AMSStatusCode=200, NSLocalizedFailureReason=The server encountered an error}}} Has anyone encountered a similar issue, or does anyone have insights into what might be causing this? I’m using StoreKit 2 methods for handling subscriptions, and this error only occurs when attempting to apply the promotional offer. Any help or suggestions would be greatly appreciated! Thanks in advance!
1
0
513
Aug ’24
Issue starting Live Activities with ActivityKit push notifications
Hi all, I'm trying to implement starting Live Activities with push notifications according to this article: https://developer.apple.com/documentation/activitykit/starting-and-updating-live-activities-with-activitykit-push-notifications I'm using Xcode 15.1 beta 3, I have run my tests on a physical device with iOS 17.2 as well as the simulator with iOS 17.2 My problem is I can't seem to be able to get the pushToStartToken needed to start the live activities. I have subscribed to the pushToStartTokenUpdates but I never get any updates. Here is the code I used: Task { do { for try await data in Activity<DailyGoalActivityAttributes>.pushToStartTokenUpdates { let token = data.map {String(format: "%02x", $0)}.joined() print("Activity token: \(token)") } } catch { print(error) } } Any help would be greatly appreciated. Thanks, HS
12
5
5.6k
Nov ’23
BGTaskScheduler with
I’m trying to use BGProcessingTaskRequest to fetch step data in the background and send it. However, when I combine BGProcessingTaskRequest, HKObserverQuery, and healthStore.enableBackgroundDelivery, the results sometimes return zero. When I don’t schedule the BGProcessingTaskRequest, the data retrieved using HKObserverQuery and HKSampleQueryDescriptor is correct. // Register Smart Walking Sync Task func registerSmartWalkingSync() { #if !targetEnvironment(simulator) BGTaskScheduler.shared.register(forTaskWithIdentifier: BGTaskIdentifier.smartwalking.rawValue, using: nil) { task in guard let task = task as? BGProcessingTask else { return } self.handleSmartWalkingSync(task: task) } #endif } func scheduleSmartWalkingSync(in seconds: TimeInterval? = nil, at date: Date? = nil) { let newRequest = BGProcessingTaskRequest(identifier: BGTaskIdentifier.smartwalking.rawValue) newRequest.requiresNetworkConnectivity = true newRequest.requiresExternalPower = false if let seconds = seconds { newRequest.earliestBeginDate = Date().addingTimeInterval(seconds) } else if let date = date { newRequest.earliestBeginDate = date } do { try BGTaskScheduler.shared.submit(newRequest) debugPrint("✅ [BGTasksManager] scheduled for Smart Walking Sync") } catch { FirebaseConnection.shared.recordException(error) debugPrint("❌ [BGTasksManager] error: \(error)") } } // Handle Smart Walking Sync Task func handleSmartWalkingSync(task: BGProcessingTask) { debugPrint("🔄 [BGTasksManager] sync \(task.identifier) sync started") scheduleSmartWalkingSync(in: SYNC_SMARTWALKING_TIME_INTERVAL) let queue = OperationQueue() let operation = HealthActivitiesOperation() operation.completionBlock = { Task { do { try await operation.sync() task.setTaskCompleted(success: !operation.isCancelled) debugPrint("✅ [BGTasksManager] sync \(task.identifier) completed successfully") } catch { FirebaseConnection.shared.recordException(error) task.setTaskCompleted(success: false) debugPrint("❌ [BGTasksManager] sync \(task.identifier) error: \(error)") } } } task.expirationHandler = { operation.cancel() } queue.addOperation(operation) } // MARK: - HealthKit Background Delivery internal func enableBackgroundDeliveryForAllTypes() async throws { for type in allTypes.filter({ type in type != HKQuantityType(.heartRate) }) { try await healthStore.enableBackgroundDelivery(for: type, frequency: .daily) } debugPrint("✅ [HealthKitManager] Enable Background Delivery") } internal func observeHealthKitQuery(predicate: NSPredicate?) async throws -> Set<HKSampleType> { let queryDescriptors: [HKQueryDescriptor] = allTypes .map { type in HKQueryDescriptor(sampleType: type, predicate: predicate) } return try await withCheckedThrowingContinuation { continuation in var hasResumed = false let query = HKObserverQuery(queryDescriptors: queryDescriptors) { query, updatedSampleTypes, completionHandler, error in if hasResumed { return } if let error = error { continuation.resume(throwing: error) } else { continuation.resume(returning: updatedSampleTypes ?? []) } hasResumed = true completionHandler() } healthStore.execute(query) } } internal func getHealthActivity(by date: Date, predicate: NSCompoundPredicate, sampleTypes: Set<HKSampleType>) async throws -> HealthActivityData { var data = HealthActivityData(steps: 0, calories: 0, distance: 0.0, distanceCycling: 0.0, totalDuration: 0, date: date, heartRate: nil) for sampleType in sampleTypes { guard let quantityType = sampleType as? HKQuantityType else { continue } switch quantityType { case HKQuantityType(.stepCount): let stepCount = try await getDescriptor( date: date, type: quantityType ).result(for: healthStore) .statistics(for: date)?.sumQuantity()?.doubleValue(for: HKUnit.count()) data.steps = stepCount ?? 0.0 // Calculate total duration using HKSampleQueryDescriptor let totalDurationDescriptor = HKSampleQueryDescriptor( predicates: [.quantitySample(type: quantityType, predicate: predicate)], sortDescriptors: [SortDescriptor(\.endDate, order: .reverse)] ) let stepSamples = try await totalDurationDescriptor.result(for: healthStore) data.totalDuration += stepSamples .reduce(0) { $0 + $1.endDate.timeIntervalSince($1.startDate) } / 60.0 default: debugPrint("Unknown quantity type") } } return data }
2
0
361
Aug ’24
How can I share code between app and widget that contains uiapplication?
OK, so I'm trying to share some utils classes for logging. The problem is a use-case where I want to create a debug notification. However, inside the app, I want to show a popup instead if the app is showing, but I can't share that code because it uses UIApplication.shared.ApplicationState. I've tried gating it off with all sorts of methods, @available etc. but I get compilation error "unavailable for application extensions" Example of me trying: static func doNotification(_ header: String, message: String) { //so I'm trying to gate off the code that only can be called in an extension , and in addition I have @available below if(isAppExtension()){ doNotificationFromExtension(header, message: message) }else{ doNotificationFromApp(header, message: message) } } @available(iOSApplicationExtension, unavailable) static func doNotificationFromApp(_ header: String, message: String) { let state = UIApplication.shared.applicationState if state != .active { //my dialog handler in-app popup }else{ NotifUtils.createLocalNotification(message, header: header, category: NOTIFICATION_CATEGORY_DEBUG, playSound: false) } } //here I know that I'm in an extension, so app isn't showing - always local notification static func doNotificationFromExtension(_ header: String, message: String) { NotifUtils.createLocalNotification(message, header: header, category: NOTIFICATION_CATEGORY_DEBUG, playSound: false) } static func isAppExtension() -> Bool { return Bundle.main.executablePath?.contains(".appex/") ?? false } Is there any way to share the code like this? The reason I want to do this is because I have various live activity code that I'd want to re-use, but this is a show.-stopper.
3
0
419
Aug ’24
PTT framework problem after idle ( recording muted by OS )kaj23
We have been successfully using the PTT (Push-to-Talk) framework in our application since the release of iOS 17. Audio is recorded by pressing a PTT button and speaking after the PTT framework initiates an AVAudioSession. While the PTT framework has generally worked well since the iOS 17 release, we have received reports that, on occasion, after the app has been idle for a while ( when I have seen it my phone has been in flightmode over night), it suddenly records only silent audio. This issue does not occur every time but sporadically. For users experiencing this problem, pressing the PTT button results in no “PTT framework start sound,” and only “empty sound” is recorded. The only solution to restore audio is restarting the device. Restarting the app alone is insufficient, though leaving the PTT channel and rejoining it also resolves the issue. I have reproduced the problem several times and observed that everything appears normal within the app. We receive an active AVAudioSession from the PTT framework, and it seems like the app is recording, but all recorded sound packets are silent. Upon reviewing logs from the phone (via the Console app), I noticed that the app is muted when starting the recording and unmuted after stopping the recording. For example: • Start recording ≈ 15:01:30 • Stop recording ≈ 15:01:44 • 15:01:30.124144+0100 audiomxd -CMSessionMgr- MXCoreSessionSetProperty: Session ‘sid:0xa80037, AppName(2717), ‘prim’’ isRecordingMuted updated to ‘1’ • 15:01:44.384208+0100 audiomxd -CMSessionMgr- MXCoreSessionSetProperty: Session ‘sid:0xa80037, AppName(2717), ‘prim’’ isRecordingMuted updated to ‘0’ When the system functions normally, the isRecordingMuted flag toggles between 0 and 1, but remains at 0 (non-muted) during recording. After stopping the recording, this state does not change anymore, unlike in the error state. There is no difference in behavior whether the app is in the foreground or background when starting the transmission, or whether the PTT framework’s “Talk” button is used once the device enters the “error state.” I have filed a bug report with logs provided on 28 November 2023 that is still open but no feedback. We now have customers that are reporting this issue again on 17.5.1 and its starting to be a big issue. Anyone else that have similar problems ?
0
0
297
Aug ’24
Error in OutlineListView on MAC OS 15..1 with Swifdata recursive relationship
I have a model "Objetive" with recursive iteration. In the user interface I can see all the Items, as expected, and I can expands all those that have children. However, I encounter an error when attempting to compact anyone with children that I have previously expanded, But only when I'm using Mac OS 15.1 On iOS 18.1 Works perfectly. The error happens in List, Outlinegroup or Table. struct ObjectiveTable: View{ @Query(filter: #Predicate<Objective>{$0.parent == nil}) var all : [Objective] @State var selected : Objective? var body: some View{ VStack{ List(all ,children: \Objective.sonsNIL){ line in Text(line.name) } } } } @Model final class Objective{ @Attribute(.unique) var id = UUID() var name: String var parent: Objective? = nil @Relationship(deleteRule: .cascade, inverse: \Objective.parent) var sons: [Objective] = [] var sonsNIL: [Objective]?{ get{ if sons.count < 1{ return nil } else{ return sons } } } ... ERROR Row index -1 out of row range (numberOfRows: 14) for <SwiftUI.SwiftUIOutlineListView: 0x129852200> ( 0 CoreFoundation 0x000000018c834ec0 __exceptionPreprocess + 176 1 libobjc.A.dylib 0x000000018c31acd8 objc_exception_throw + 88 2 AppKit 0x00000001903eb304 -[NSTableRowData availableRowViewWhileUpdatingAtRow:] + 0 3 SwiftUI 0x00000001bb365224 $s7SwiftUI0A17UIOutlineListViewC11removeItems2at8inParent13withAnimationy10Foundation8IndexSetV_ypSgSo07NSTableeL7OptionsVtF + 1388 4 SwiftUI 0x00000001bb3656f8 $s7SwiftUI0A17UIOutlineListViewC11removeItems2at8inParent13withAnimationy10Foundation8IndexSetV_ypSgSo07NSTableeL7OptionsVtFTo + 252 5 CoreFoundation 0x000000018c7a28b4 invoking + 148 6 CoreFoundation 0x000000018c7a272c -[NSInvocation invoke] + 428 7 CoreFoundation 0x000000018c7d7958 -[NSInvocation invokeWithTarget:] + 64 8 AppKit 0x000000019052a110 -[NSObjectAnimator forwardInvocation:] + 1512 9 CoreFoundation 0x000000018c7a0ee4 forwarding + 964 10 CoreFoundation 0x000000018c7a0a60 CF_forwarding_prep_0 + 96 11 SwiftUI 0x00000001bb37e458 $s7SwiftUI22OutlineListCoordinatorC19recursivelyDiffRows_4with2by9expandAllyAA0a9UIOutlineD4ViewC_AA0dC4ItemCAA0nD4TreeVAA14ExpansionStateOtF + 37012 12 SwiftUI 0x00000001bb3802b8 $s7SwiftUI22OutlineListCoordinatorC19recursivelyDiffRows_4with2by9expandAllyAA0a9UIOutlineD4ViewC_AA0dC4ItemCAA0nD4TreeVAA14ExpansionStateOtF + 44788 13 SwiftUI 0x00000001bb37538c $s7SwiftUI22OutlineListCoordinatorC8diffRows2of2toyAA0a9UIOutlineD4ViewC_AA0kD4TreeVtF + 120 14 SwiftUI 0x00000001bb36f3d4 $s7SwiftUI22OutlineListCoordinatorC6update4diff04viewD4Tree18idSelectionChanged010navigationk4SeedL0011templateRowL011transactionySb_AA04ViewdI0VS3bAA11TransactionVtFyycfU_yyXEfU + 220 15 SwiftUI 0x00000001bb369044 $s7SwiftUI22OutlineListCoordinatorC24withSelectionUpdateGuard33_BE7B171B0BEE2A9E27ED12968C3771F8LLyySS_yyXEtF + 1320 16 SwiftUI 0x00000001bb36f2d4 $s7SwiftUI22OutlineListCoordinatorC6update4diff04viewD4Tree18idSelectionChanged010navigationk4SeedL0011templateRowL011transactionySb_AA04ViewdI0VS3bAA11TransactionVtFyycfU + 708 17 SwiftUICore 0x00000002277cb578 $sIeg_ytIegr_TRTA + 28 18 SwiftUICore 0x0000000227a6d2b8 $s7SwiftUI6UpdateO15dispatchActionsyyFZ + 1236 19 SwiftUICore 0x0000000227a6c79c $s7SwiftUI6UpdateO3endyyFZ + 212 20 SwiftUICore 0x0000000227f6061c $sSo9NSRunLoopC7SwiftUIE11addObserveryyyycFZySo05CFRunbF3RefaSg_So0gB8ActivityVSvSgtcfU_Tf4ddd_n + 176 21 CoreFoundation 0x000000018c7c17a8 CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 36 22 CoreFoundation 0x000000018c7c1694 __CFRunLoopDoObservers + 552 23 CoreFoundation 0x000000018c7c0380 CFRunLoopRunSpecific + 648 24 HIToolbox 0x0000000197c000cc RunCurrentEventLoopInMode + 292 25 HIToolbox 0x0000000197c05d1c ReceiveNextEventCommon + 220 26 HIToolbox 0x0000000197c06020 _BlockUntilNextEventMatchingListInModeWithFilter + 76 27 AppKit 0x0000000190303650 _DPSNextEvent + 660 28 AppKit 0x0000000190c2a408 -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 688 29 AppKit 0x00000001902f675c -[NSApplication run] + 480 30 AppKit 0x00000001902cd02c NSApplicationMain + 888 31 SwiftUI 0x00000001ba77045c $s7SwiftUI6runAppys5NeverOSo21NSApplicationDelegate_So11NSResponderCXcFTf4e_nAA07TestingdG0C_Tg5Tm + 160 32 SwiftUI 0x00000001babf4854 $s7SwiftUI6runAppys5NeverOxAA0D0RzlF + 84 33 SwiftUI 0x00000001baf04134 $s7SwiftUI3AppPAAE4mainyyFZ + 224 34 Marlo SystemManagement.debug.dylib 0x0000000100ce6130 $s22Marlo_SystemManagement0a1_bC3AppV5$mainyyFZ + 40 35 Marlo SystemManagement.debug.dylib 0x0000000100ce61fc __debug_main_executable_dylib_entry_point + 12 36 dyld 0x000000018c358274 start + 2840 ) FAULT: NSTableViewException: Row index -1 out of row range (numberOfRows: 14) for <SwiftUI.SwiftUIOutlineListView: 0x129852200>; (user info absent)
0
1
253
Aug ’24
Swift 6 concurrency - Xcode 16b5 - init() is always nonisolated?
I noticed a change from previous betas when I attempted to compile my code with Xcode 16 beta 5. If I have a class that is MainActor isolated, and it overrides init(), it looks like this init is always considered nonisolated now, even for a MainActor isolated class. This was not the case before. For example, I have a class that inherits from NSScroller. It defines a default initializer init() which calls the designated initializer - super.init(frame:CGRect()). This is apparently not allowed right now. If that's the case, how can one even default-initialize a class??? It also doesn't let me initialize other properties, since everything is MainActor isolated. Here's an abbreviated example. class MyCustomScroller : NSScroller { init () { super.init(frame: CGRect()) scrollerStyle = .overlay alphaValue = 0 } } This was allowed in prior betas. However, in beta 5, all 3 lines of my init generates an error such as: Call to main actor-isolated initializer 'init(frame:)' in a synchronous nonisolated context or Main actor-isolated property 'scrollerStyle' can not be mutated from a nonisolated context Is it just no longer possible to default-initialize MainActor classes, such as NSViews, now? The first line is particularly problematic because if I change it to just call super.init() then I get this error instead: Must call a designated initializer of the superclass 'NSScroller' You must call the designated initializer ... oh wait, we won't let you. Too bad.
5
3
1.2k
Aug ’24
Wrong colours when rendering SKTexture
I am generating an SKTexture with a GKNoiseMap. When I look at the texture in a swift playground, it has the expected colours. But when I apply the texture to a material and render it in a SCNView, the colours are different (colours appear too bright). What am I doing wrong? Swift playground to reproduce the issue (look at the texture variable in the playground and compare to rendered image). - https://developer.apple.com/forums/content/attachment/68210adc-98e9-4984-bca7-01f6e658d555
4
1
1.2k
Oct ’20
Runtime race condition warning when calling PHPhotoLibrary.shared().performChanges async
I have enabled runtime concurrency warnings to check for future problems concerning concurrency: Build Setting / Other Swift Flags: -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks When trying to call the async form of PHPhotoLibrary.shared().performChanges{} I get the following runtime warning: warning: data race detected: @MainActor function at ... was not called on the main thread in the line containing performChanges. My sample code inside a default Xcode multi platform app template is as follows: import SwiftUI import Photos @MainActor class FotoChanger{     func addFotos() async throws{         await PHPhotoLibrary.requestAuthorization(for: .addOnly)         try! await PHPhotoLibrary.shared().performChanges{             let data = NSDataAsset(name: "Swift")!.data             let creationRequest = PHAssetCreationRequest.forAsset()             creationRequest.addResource(with: .photo, data: data, options: PHAssetResourceCreationOptions())         }     } } struct ContentView: View {     var body: some View {         ProgressView()             .task{                 try! await FotoChanger().addFotos()             }     } } You would have to have a Swift data asset inside the asset catalog to run the above code, but the error can even be recreated if the data is invalid. But what am I doing wrong? I have not found a way to run perform changes, the block or whatever causes the error on the main thread. PS: This is only test code to show the problem, don't mind the forced unwraps.
1
0
1.7k
Feb ’22
Sudden errors that never happened before
Hello, I've been working on my macos app for months, today I opened XCode, and it's full of the same errors "Value of type 'URL' has no member 'url''" and "Cannot convert value of type 'Binding' to expected argument type 'CGFloat'". I didn't change ANYTHING, I didn't update nor remove anything, the 3rd party module I'm using didn't get updated, this is all out of the blue! I tried to clean the build folder, erase the derivated data, rebuild a new project, these errors won't go away...worst part is that another of my app use the same codes and there I see the errors but the app still compiles and build!!
0
0
282
Aug ’24
.onMove does not work properly
Hello, I have a problem with the .onMove function. I believe I have set everything up properly. However, the moving does not seem to be working correctly. When I try to move the item, it is highlighted first, as it is supposed to be. Then, while I am moving it through the list, it disappears for some reason, and at the end of the move, it comes back to its initial place. (I use iOS 16.0 minimum, so I don't have to include the EditButton(). It works the same in the edit mode tho) import SwiftUI struct Animal: Identifiable { var id = UUID() var name: String } struct ListMove: View { @State var animals = [Animal(name: "Dog"), Animal(name: "Cat"), Animal(name: "Cow"), Animal(name: "Goat"), Animal(name: "Chicken")] var body: some View { List { ForEach(animals) { animal in Text(animal.name) } .onMove(perform: move) } } func move(from source: IndexSet, to destination: Int) { animals.move(fromOffsets: source, toOffset: destination) } } #Preview { ListMove() }
2
0
348
Aug ’24
Strange visionOS Simulator
I found that my visionOS Simulator is very strange. Many functions and features are missing. For example, I learned from the Internet that the immersive scenes of Environments in their visionOS Simulator can be opened, but I click There was no response after the attack. There are not only these, but also many system features. I saw on the Internet that other developers have them, and I am missing. I'm worried that this will have an impact on me when testing my app. May I ask why? Some information: My updated Xcode version is the latest Xcode15.1Beta. Device: iMac (2021) Simulator system number: 21N305
1
0
556
Jan ’24
Swift Cocoa: PrintOperation() with Sonoma does not work
I have a Swift Coco program taht print a NSView. It work perfectly fine in Monterey but does show the print panel in Sonoma. I cannot find the problem. Here are the 4 errors: Failed to connect (genericPrinterImage) outlet from (PMPrinterSelectionController) to (NSImageView): missing setter or instance variable Failed to connect (otherPrintersLabel) outlet from (PMPrinterSelectionController) to (NSTextField): missing setter or instance variable Failed to connect (localPrintersLabel) outlet from (PMPrinterSelectionController) to (NSTextField): missing setter or instance variable Failed to connect (genericPrinterImage) outlet from (PMPrinterSelectionController) to (NSImageView): missing setter or instance variable func createPrintOperation() { let printOpts: [NSPrintInfo.AttributeKey: Any] = [ .headerAndFooter: false, .orientation: NSPrintInfo.PaperOrientation.portrait ] let printInfo = NSPrintInfo(dictionary: printOpts) printInfo.leftMargin = 0 printInfo.rightMargin = 0 printInfo.topMargin = 0 printInfo.bottomMargin = 0 printInfo.horizontalPagination = .fit printInfo.verticalPagination = .automatic printInfo.isHorizontallyCentered = true printInfo.isVerticallyCentered = true printInfo.scalingFactor = 1.0 printInfo.paperSize = NSMakeSize(612, 792) // Letter size // Create a print operation with the view you want to print , myPrintView is a NSView let printOperation = NSPrintOperation(view: myPrintView, printInfo: printInfo) // Configure the print panel printOperation.printPanel.options.insert(NSPrintPanel.Options.showsPaperSize) printOperation.printPanel.options.insert(NSPrintPanel.Options.showsOrientation) // Set the job title for the print operation let jobTitle = fact.nom_complet_f.replacingOccurrences(of: " ", with: "") printOperation.jobTitle = jobTitle // Run the print operation printOperation.run() }
2
0
237
Aug ’24
Implement UNUserNotificationCenterDelegate in iOS app using Swift6
I've got a problem with compatibility with Swift6 in iOS app that I have no idea how to sort it out. That is an extract from my main app file @MainActor @main struct LangpadApp: App { ... @State private var notificationDataProvider = NotificationDataProvider() @UIApplicationDelegateAdaptor(NotificationServiceDelegate.self) var notificationServiceDelegate var body: some Scene { WindowGroup { TabView(selection: $tabSelection) { ... } .onChange(of: notificationDataProvider.dateId) { oldValue, newValue in if !notificationDataProvider.dateId.isEmpty { tabSelection = 4 } } } } init() { notificationServiceDelegate.notificationDataProvider = notificationDataProvider } } and the following code shows other classes @MainActor final class NotificationServiceDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var notificationDataProvider: NotificationDataProvider? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -&gt; Bool { UNUserNotificationCenter.current().delegate = self return true } func setDateId(dateId: String) { if let notificationDataProvider = notificationDataProvider { notificationDataProvider.dateId = dateId } } nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async { // After user pressed notification let content = response.notification.request.content if let dateId = content.userInfo["dateId"] as? String { await MainActor.run { setDateId(dateId: dateId) } } } nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -&gt; UNNotificationPresentationOptions { // Before notification is to be shown return [.sound, .badge, .banner, .list] } } @Observable final public class NotificationDataProvider : Sendable { public var dateId = "" } I have set Strict Concurrency Checking to 'Complete.' The issue I'm facing is related to the delegate class method, which is invoked after the user presses the notification. Current state causes crash after pressing notification. If I remove "nonisolated" keyword it works fine but I get the following warning Non-sendable type 'UNNotificationResponse' in parameter of the protocol requirement satisfied by main actor-isolated instance method 'userNotificationCenter(_:didReceive:)' cannot cross actor boundary; this is an error in the Swift 6 language mode I have no idea how to make it Swift6 compatible. Does anyone have any clues?
0
11
533
Aug ’24
AppStorage extension for Bool Arrays
Hi, As AppStorage does not support arrays, I found an extension online that allows for handling arrays of strings with AppStorage. However, in my use case, I need to handle arrays of boolean values. Below is the code. Any help would be greatly appreciated. extension Array: RawRepresentable where Element: Codable { public init?(rawValue: String) { guard let data = rawValue.data(using: .utf8), let result = try? JSONDecoder().decode([Element].self, from: data) else { return nil } self = result } public var rawValue: String { guard let data = try? JSONEncoder().encode(self), let result = String(data: data, encoding: .utf8) else { return "[]" } return result } }
1
0
319
Aug ’24
[WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. What does this mean?
Getting this error several times when presenting a modal window over my splitview window when running it on my Mac using Swift/Mac Catalyst in XCode 14.2. When I click the Cancel button in the window then I get Scene destruction request failed with error: (null) right after an unwind segue. 2023-07-04 16:50:45.488538-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.488972-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.496702-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.496800-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.994147-0500 Recipes[27836:1295134] Unbalanced calls to begin/end appearance transitions for <UINavigationController: 0x7f7fdf068a00>. bleep 2023-07-04 16:51:00.655233-0500 Recipes[27836:1297298] Scene destruction request failed with error: (null) I don't quite understand what all all this means. (The "bleep" was a debugging print code I put in the unwind segue). I'm working through Apple's Mac Catalyst tutorial but it seems to be riddled with bugs and coding issues, even in the final part of the completed app which I dowmloaded and ran. I don't see these problems on IPad simulator. I don't know if it's because Catalyst has problems itself or there's something else going on that I can fix myself. Any insight into these errors would be very much appreciated! PS: The app seems to run ok on Mac without crashing despite the muliple issues
4
3
1.4k
Jul ’23
Sign in with Apple button dark mode in Swift
I implemented Sign in with Apple but in all cases the button is always black. I would like to show it in light/ dark mode depending on the phone settings. This is my code: class MyAuthorizationAppleIDButton: UIButton { private var authorizationButton: ASAuthorizationAppleIDButton! @IBInspectable var cornerRadius: CGFloat = 3.0 @IBInspectable var authButtonType: Int = ASAuthorizationAppleIDButton.ButtonType.default.rawValue @IBInspectable var authButtonStyle: Int = ASAuthorizationAppleIDButton.Style.black.rawValue override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func draw(_ rect: CGRect) { super.draw(rect) // Create ASAuthorizationAppleIDButton authorizationButton = ASAuthorizationAppleIDButton(authorizationButtonType: .signIn, authorizationButtonStyle: .black) let type = ASAuthorizationAppleIDButton.ButtonType.init(rawValue: authButtonType) ?? .default let style = ASAuthorizationAppleIDButton.Style.init(rawValue: authButtonStyle) ?? .black authorizationButton = ASAuthorizationAppleIDButton(authorizationButtonType: type, authorizationButtonStyle: style) authorizationButton.cornerRadius = cornerRadius // Show authorizationButton addSubview(authorizationButton) // Use auto layout to make authorizationButton follow the MyAuthorizationAppleIDButton's dimension authorizationButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ authorizationButton.topAnchor.constraint(equalTo: self.topAnchor, constant: 0.0), authorizationButton.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0.0), authorizationButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0.0), authorizationButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0.0), ]) } } So basically with the code above, I can set on Storyboard the style of the button but it seems that even if I change the value at my code, the result is based on what I chose on Storyboard's variable. Is there any solution where I would be able to show the button in light/ dark mode depending on the phone settings ?
2
1
939
Jul ’23
Interface fails to work because I have a class named Context.
Bug When you try to extend from NSViewRepresentable but you have a class named Context swift throws a error message that doesn't help at all. Type 'MetalViewRepresentable' does not conform to protocol 'NSViewRepresentable' Steps to reproduce Create a MacOS App Copy this code struct MetalViewRepresentable: NSViewRepresentable { @Binding var metalView: MTKView func makeNSView(context: Context) -> some NSView { metalView } func updateNSView(_ uiView: NSViewType, context: Context) { } } Write this line of code in any file class Context {}
0
0
215
Aug ’24