Hi, I'm relatively new to iOS development and kindly ask for some feedback on a strategy to achieve this desired behavior in my app.
My Question:
What would be the best strategy for sound effect playback when an app is in the background with precise timing? Is this even possible?
Context:
I created a basic countdown timer app (targeting iOS 17 with Swift/SwiftUI.). Countdown sessions can last up to 30-60 mins. When the timer is started it progresses through a series of sub-intervals and plays a short sound for each one. I used AVAudioPlayer and everything works fine when the app is in the foreground. I'm considering switching to AVAudioEngine b/c precise timing is very important and the AIs tell me this would have better precision.
I'm already setting "App plays audio or streams audio/video using AirPlay" in my Plist, and have configured:
AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .mixWithOthers)
Curiously, when testing on my iPhone 13 mini, sounds sometimes still play when the app is in the background, but not always.
What I've considered:
Background Tasks: Would they make any sense for this use-case? Seems like not if the allowed time is short & limited by the system.
Pre-scheduling all Sounds: Not sure this would even work and seems like a lot of memory would be needed (could be hundreds of intervals).
ActivityKit Alerts: works but with a ~50ms delay which is too long for my purposes.
Pre-Render all SFX to 1 large audio file: Seems like a lot of work and processing time and probably not worth it. I hope there's a better solution.
I'd really appreciate any feedback.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I’m experiencing a crash at runtime when trying to extract audio from a video. This issue occurs on both iOS 18 and earlier versions. The crash is caused by the following error:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '*** -[AVAssetExportSession exportAsynchronouslyWithCompletionHandler:] Cannot call exportAsynchronouslyWithCompletionHandler: more than once.
(0x1851435ec 0x1826dd244 0x1970c09c0 0x214d8f358 0x214d95899 0x190a1c8b9 0x214d8efd9 0x30204cef5 0x302053ab9 0x190a5ae39)
libc++abi: terminating due to uncaught exception of type NSException
My previous code worked fine, but it's crashing with Swift 6.
Does anyone know a solution for this?
Previous code:
func extractAudioFromVideo(from videoURL: URL, exportHandler: ((AVAssetExportSession, CurrentValueSubject<Float, Never>?) -> Void)? = nil, completion: @escaping (Swift.Result<URL, Error>) -> Void) {
let asset = AVAsset(url: videoURL)
// Create an AVAssetExportSession to export the audio track
guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) else {
completion(.failure(NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to create AVAssetExportSession"])))
return
}
// Set the output file type and path
guard let filename = videoURL.lastPathComponent.components(separatedBy: ["."]).first else { return }
let outputURL = VideoUtils.getTempAudioExportUrl(filename)
VideoUtils.deleteFileIfExists(outputURL.path)
exportSession.outputFileType = .m4a
exportSession.outputURL = outputURL
let audioExportProgressPublisher = CurrentValueSubject<Float, Never>(0.0)
if let exportHandler = exportHandler {
exportHandler(exportSession, audioExportProgressPublisher)
}
// Periodically check the progress of the export session
let timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
audioExportProgressPublisher.send(exportSession.progress)
}
// Export the audio track asynchronously
exportSession.exportAsynchronously {
switch exportSession.status {
case .completed:
completion(.success(outputURL))
case .failed:
completion(.failure(exportSession.error ?? NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unknown error occurred while exporting audio"])))
case .cancelled:
completion(.failure(NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Export session was cancelled"])))
default:
completion(.failure(NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unknown export session status"])))
}
// Invalidate the timer when the export session completes or is cancelled
timer.invalidate()
}
}
## New Code:
func extractAudioFromVideo(from videoURL: URL, exportHandler: ((AVAssetExportSession, CurrentValueSubject<Float, Never>?) -> Void)? = nil, completion: @escaping (Swift.Result<URL, Error>) -> Void)
{
let asset = AVAsset(url: videoURL)
// Create an AVAssetExportSession to export the audio track
guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) else {
completion(.failure(NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to create AVAssetExportSession"])))
return
}
// Set the output file type and path
guard let filename = videoURL.lastPathComponent.components(separatedBy: ["."]).first else { return }
let outputURL = VideoUtils.getTempAudioExportUrl(filename)
VideoUtils.deleteFileIfExists(outputURL.path)
exportSession.outputFileType = .m4a
exportSession.outputURL = outputURL
let audioExportProgressPublisher = CurrentValueSubject<Float, Never>(0.0)
if let exportHandler {
exportHandler(exportSession, audioExportProgressPublisher)
}
let task = Task {
if #available(iOS 18.0, *) {
// Handle export for iOS 18 and later
let states = exportSession.states(updateInterval: 0.1)
for await state in states {
switch state {
case .pending, .waiting:
break
case .exporting(progress: let progress):
print("Exporting: \(progress.fractionCompleted)")
if progress.isFinished {
completion(.success(outputURL))
} else if progress.isCancelled {
completion(.failure(NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Export session was cancelled"])))
} else {
audioExportProgressPublisher.send(Float(progress.fractionCompleted))
}
}
}
try await exportSession.export(to: outputURL, as: .m4a) // Only call export once
} else {
// Handle export for iOS versions below 18
let publishTimer = Timer.publish(every: 0.1, on: .main, in: .common)
.autoconnect()
.sink { [weak exportSession] _ in
guard let exportSession = exportSession else { return }
audioExportProgressPublisher.send(exportSession.progress)
}
// Only call export once
await exportSession.export()
// Handle the export session's status
switch exportSession.status {
case .completed:
completion(.success(outputURL))
case .failed:
completion(.failure(exportSession.error ?? NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unknown error occurred while exporting audio"])))
case .cancelled:
completion(.failure(NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Export session was cancelled"])))
default:
completion(.failure(NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unknown export session status"])))
}
// Invalidate the timer when the export session completes or is cancelled
publishTimer.cancel()
}
}
task.cancel()
}
Topic:
Programming Languages
SubTopic:
Swift
Does SwiftUI now support the ability for a chart to have two different Y Axes? ChaptGPT seems to think it does, but I keep getting compiler errors in XCode.
I recently encountered an issue with Xcode 16.2 while attempting to integrate Settings.bundle into a new app. I added Settings.bundle as a new file (using the provided template), but when I ran the app (the standard simple "Hello World" project), the expected three default controls (Name, Enabled, Slider) did not appear in the app's settings.
To troubleshoot, I downgraded my system to macOS Sonoma 14.7.2 and Xcode 15.4 (on a 2023 Mac Mini, M2). After this downgrade, everything worked as expected. With a new project, adding Settings.bundle, and running the app, the settings entry for the app appeared, including the three default fields.
This behavior suggests a potential issue or incompatibility with Xcode 16.2.
I have been recently getting the following error seemingly randomly, when an event handler of a SwiftUI view accesses a relationship of a SwiftData model the view holds a reference to. I haven't yet found a reliable way of reproducing it:
SwiftData/BackingData.swift:866: Fatal error: This model instance was invalidated
because its backing data could no longer be found the store.
PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: COREDATA_ID_URL),
implementation: SwiftData.PersistentIdentifierImplementation)
What could cause this error? Could you suggest me a workaround?
Hi There,
I have a iOS App which has been published and purely managing data by SwiftData. I use following simple codes everywhere in Views:
...
@Query var items: [Item]
....
if let firstItem = items.first( where: {...}) {
...
Then I encountered crash at Query that _items.wrapperdValue has some errors.
Then I tried to split first(where...) into ordinary way:
let filteredItems = items.filter(...)
if let firstItem = filteredItems.first {
...
It runs OK.
Is it a bug in SwiftData in 18.2 or I missed some steps to facilitate SwiftData macros?
Hello, everyone!
Help me please to find answer. I have two applications: App-1 with share extension and App-2 without it. From the second app I can open share extension via UIActivityViewController. But I need this extension in the second application to open immediately by pressing a button, and not through UIActivityViewController. Can I do this?
Given the below code with Swift 6 language mode, Xcode 16.2
If running with iOS 18+: the app crashes due to _dispatch_assert_queue_fail
If running with iOS 17 and below: there is a warning: warning: data race detected: @MainActor function at Swift6Playground/PublishedValuesView.swift:12 was not called on the main thread
Could anyone please help explain what's wrong here?
import SwiftUI
import Combine
@MainActor
class PublishedValuesViewModel: ObservableObject {
@Published var count = 0
@Published var content: String = "NA"
private var cancellables: Set<AnyCancellable> = []
func start() async {
let publisher = $count
.map { String(describing: $0) }
.removeDuplicates()
for await value in publisher.values {
content = value
}
}
}
struct PublishedValuesView: View {
@ObservedObject var viewModel: PublishedValuesViewModel
var body: some View {
Text("Published Values: \(viewModel.content)")
.task {
await viewModel.start()
}
}
}
I have a VPN application published in the app store. Used Ikev2 for this personal VPN. There are two in-app purchases. One is 'Monthly' and another is 'Yearly' with 3 days free trial. We have seen something strange for the yearly subscriptions which has free trail, the cancellation reason through the billing issue is too high like 70-80% due to billing retry state. Some other apps which have billing issues under 10% always. We have done some research and found that if the user doesn't cancel and Apple is unable to charge then it goes to a billing retry state.
If users don't like the app, they could cancel their subscription/free trail easily but they are not doing this and why Apple unable to charge the bill after the trial ends. Am i missing something in the developer end?
Hi
In C#, one can define associated functions by the following.
Notice that "Declarations DE" is a reference to a function in another C# project file. This lets the compiler know that there are other references in the project.
Likewise, "Form_Load" is the entry point of the code, similar to "main" in C. Any calls to related functions can be made in this section, to the functions that have been previously defined above.
So I set out trying to find similar information about SwiftUI, and found several, but only offer partial answers to my questions.
The YouTube video...
Extracting functions and subviews in SwiftUI | Bootcamp #20 - YouTube
... goes into some of the details, but still leaves me hanging.
Likewise...
SOLVED: Swift Functions In Swift UI – SwiftUI – Hacking with Swift forums
... has further information, but nothing concrete that I am looking for.
Now in the SwiftUI project, I tried this...
The most confusing thing for me, is where is "main"?
I found several examples that call functions from the structure shown above, BUT I have no reason as to why.
So one web example on StackOverFlow called the function from position 1. That did not work.
Position 2 worked to call the function at position 3, but really, why?
All this activity brings up a lot of questions for me, such as:
Does SwiftUI need function callouts similar to C#, and they are called out even before running "main". I seem to recall Borland Delphi being this way as well.
How does SwiftUI make references to other classes (places where other functions are stored in separate files)?
Does SwiftUI actually make use of "main" in the normal sense, i.e. similar to C, C#, Rust and so on?
I did notice that once a SwiftUI function is called, it makes reference to data being passed very similar to other languages, at least for the examples I found.
Note that I looked at official SwiftUI documentation, but did not come across information that answers the above.
Topic:
Programming Languages
SubTopic:
Swift
iOS18.2 / iPhone 16pro / Xcode 16.2
'traitCollectionDidChange'
This function has been deprecated since ios17.
However, in ios18, when I changed the app to the background state or changed it to the foreground state again, it was confirmed that the function worked.
It hasn't been confirmed in ios17, but why is it only confirmed in ios18?
iOS18.2 / iPhone16 pro / xcode16.2
'traitCollectionDidChange'
This function has been deprecated in iOS17.
However, when I debugged it, I confirmed that it is not called on iOS17, but it is called on iOS18.2.
What is the reason?
I just added a .systemLarge widget to my app, but I can't get Links to work. I want the user to be able to tap one of the four rows in my widget - like the EmojiRangers example - but I can't get it to work.
I watched a Developer video from WWDC20: https://developer.apple.com/videos/play/wwdc2020/10036?time=223
The guy, Izzy, 'simply' embeds an HStack in a Link, and hey presto! It all works. But that doesn't happen for me. There's clearly some code in the background that runs.
I already have .widgetURL working for .systemSmall and .systemMedium widgets, and I don't need to use Links on those two types. Those work by sending a URL to .onOpenURL { incomingURL in ... All good there, no issues.
I've wrapped each row in the large widget in a Link with the URL of something like myappurlscheme://widgetTapped/widgetId (it's the same url as that used in the small and medium widgets). I build & run. I tap a row. It doesn't act as though a row is tappable (it doesn't go slightly transparent), and just opens the app without hitting .onOpenURL or anything else. Nothing in my scene delegate is triggered. Is there a specific delegate method that gets called? Do I need to set up some awful intents?
I'm not using any sort of NavigationStack here; that model doesn't fit my app.
Any ideas? Thanks.
I'm primarily an AppleScript writer and only a novice programmer, using ChatGPT to help me with the legwork. It has helped me to write a functioning app that builds a menu structure based on the scripts I have in the Scripts directory used in the script menu and then runs the applescripts. When I distribute the app to my desktop and run it, the scripts that access other apps, like InDesign will cause it to launch, but not actually do anything. I included the ids for each app in the entitlements dictionary and have given the app full disk access in system settings, but it's not functioning as I'd expect.
I know there are apps like Alfred that allow you to run scripts from a keystroke, but I'm building this for others I work with so they can also access info about each script, what it does, and how to use it from the menu, as well as key commands to run them.
Not sure what else to say, but if this sounds like a simple fix to anyone, please let me know.
I've been searching all over the web trying to find the proper way to get all records created by a specific user in CloudKit.
I am able to get the correct id using:
guard let userRecordID = try? await container.userRecordID() else { return }
I can see that the id returned is associated with records in my CloudKit dashboard. So I would expect that the following would get those records:
let predicate = NSPredicate(format: "%K == %@", #keyPath(CKRecord.creatorUserRecordID), userRecordID)
let query = CKQuery(recordType: "CKUser", predicate: predicate)
But instead when I use that query it returns nothing. It is successful but with nothing returned...
Any ideas why this would be happening?
P.S. I have also tried constructing the predicate using the reference, but I get the same result - success with no results.
P.S.2 Also worth mentioning that I am trying to get the results from the public database and I have set my CKContainer to the correct container id.
A program I wrote in Swift that uploads and downloads to a private database in iCloud is failing for downloads since the the 15.2 update.
It still works for uploads. I.e., I can download uploads made from the program under 15.2 on another computer running the same program under 15.1
The Fetch operation does not return an error, but the returnRecord is empty!
I do get the error below after the fact of the failure, don't know if it's related.
"ViewBridge to RemoteViewService Terminated: Error Domain=com.apple.ViewBridge Code=18 "(null)" UserInfo={com.apple.ViewBridge.error.hint=this process disconnected remote view controller -- benign unless unexpected, com.apple.ViewBridge.error.description=NSViewBridgeErrorCanceled}"
To be clear, I assume I do have access to the database since it works for upload under 15.2, as well as upload and download under 15.1, and from a very similar program on my iPhone (which I haven't updated yet!)
Questions? Comments?
Thanks!
Topic:
Programming Languages
SubTopic:
Swift
I noticed that when I enter the fully immersive view and then click the X button below the window, the immersive space remains active, and the only way to dismiss it is to click the digital crown. On other apps (Disney+ for example), closing out of the main window while in immersive mode also closes out the immersive space. I tried applying an onDisappear modifier to the the Modules view with a dismissImmersiveSpace, but that doesn't appear to do anything.
Any help would be appreciated.
I have an xcode project which has both cpp and swift code. In one of my usecase I am passing primitive type variables from swift to cpp by reference( primitives types list here as per the new cpp-swift interop documentation)
swift code:
// primitive check code:Bool
var x : Bool = true
// When we are passing a variable as a Reference, we need to use explicitly use'&'
student.PassBoolAsReferenceType (&x) // interop call to cpp code
print (x)
Cpp code:
void
Student::PassBoolAsReferenceType(bool &pValue) noexcept
{
std::cout << pValue << std::endl;
pValue = false;
}
The above code fails during compilation with no clear error message "Command SwiftCompile failed with a nonzero exit code"
However, all the other primitive types that I tested worked for the above code like Int, Float, Double etc. Only the Bool interop fails. Can someone explain why is it not possible for bool? I m using the new interop introduced in swift 5.9.
Hello Everyone,
I have a use case where I wanted to interpret the "Data" object received as a part of my NWConnection's recv call. I have my interpretation logic in cpp so in swift I extract the pointer to the raw bytes from Data and pass it to cpp as a UnsafeMutableRawPointer.
In cpp it is received as a void * where I typecast it to char * to read data byte by byte before framing a response.
I am able to get the pointer of the bytes by using
// Swift Code
// pContent is the received Data
if let content = pContent, !content.isEmpty {
bytes = content.withUnsafeBytes { rawBufferPointer in
guard let buffer = rawBufferPointer.baseAddress else {
// return with null data.
}
// invoke cpp method to interpret data and trigger response.
}
// Cpp Code
void InterpretResponse (void * pDataPointer, int pDataLength) {
char * data = (char *) pDataPointer;
for (int iterator = 0; iterator < pDataLength; ++iterator )
{
std::cout << data<< std::endl;
data++;
}
}
When I pass this buffer to cpp, I am unable to interpret it properly.
Can someone help me out here?
Thanks :)
Harshal
Hey team I'm facing an issue where startDate is 1 January 2025 and endDate is 31 March 2025 between this 2 dates is 90 days, but on my code is being taken as 89 days
I've seen the math of the code excludes the first partial day (from midnight to 06:00) on 2025-01-01, which results in 89 full days instead of 90 days.
startDate: 2025-01-01 06:00:00 +0000
endDate: 2025-03-31 06:00:00 +0000
this is my function
func daysBetweenDates() -> Int? {
guard let selectedStartDate = selectedStartDate?.date else { return nil }
guard let selectedEndDate = selectedEndDate?.date else { return 0 }
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.day], from: selectedStartDate, to: selectedEndDate)
return dateComponents.day
}
what I've tried is reset the hours to 0 so it can take the full day and return 90 days
like this
func daysBetweenDates() -> Int? {
guard let selectedStartDate = selectedStartDate?.date else { return nil }
guard let selectedEndDate = selectedEndDate?.date else { return 0 }
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0) ?? .current
let cleanMidNightStartDate = calendar.startOfDay(for: selectedStartDate)
let cleanMidNightEndDate = calendar.startOfDay(for: selectedEndDate.addingTimeInterval(24 * 60 * 60))
let dateComponents = calendar.dateComponents([.day], from: cleanMidNightStartDate, to: cleanMidNightEndDate)
let daysCount = dateComponents.day ?? 0
return daysCount
}
this worked for that date specifically but when I tried to change the date for example
startDate: 18 December 2024.
endDate: 18 March 2025.
between those dates we have 90 days but this function now reads 91.
what I'm looking is a cleaver solution for this problem so I can have the best posible quality code, thanks in advance!
Topic:
Programming Languages
SubTopic:
Swift