Post not yet marked as solved
Hi,
Is there math functions in Swift built in, such as Sin, Cos, Log etc ?
Kindest Regards
Post not yet marked as solved
I am working through the Getting Started with App Development and on Page 142 it has you write in the updateUI() function if else statement
lightButton.setTitle("Off", for: .normal)
and
lightButton.setTitle("On", for: .normal).
My app crashes every time after building it and running it. Image reference below. The app works perfectly fine before adding these two statements.
import UIKit
class ViewController: UIViewController {
@IBOutlet var lightButton: UIButton!
var lightOn = true
fileprivate func updateUI() {
if lightOn {
view.backgroundColor = .white
lightButton.setTitle("Off", for: .normal)
} else {
view.backgroundColor = .black
lightButton.setTitle("On", for: .normal)
}
}
@IBAction func buttonPressed(_ sender: Any) {
lightOn.toggle()
updateUI()
}
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
// Do any additional setup after loading the view.
}
}
Getting this error at the end.
libc++abi: terminating due to uncaught exception of type NSException
(lldb)
Post not yet marked as solved
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.
Post marked as Apple Recommended
Xcode13.4.1 is running properly, but after upgrading Xcode14, the debugging device reports an error: Library not loaded: / usr/lib/swift/libswiftCoreGraphics dylib, I according to the online solutions are tried, can't solve my problem, problem is ios10.3.3 equipment, unable to debug, also is unable to start the application success after packaging, Is this a problem with xcode14 itself?
Post not yet marked as solved
Greetings. I'm trying to insert objects into the managed context but I'm getting a runtime error "Thread 1: Cannot insert 'MyClass' in this managed object context because it is not found in the associated managed object model.". The code to set things up is pretty much straight from Apple -
var sharedModelContainer: ModelContainer = {
let schema = Schema([
MyClass.self,
MyOtherClass.self
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
The context is being accessed through the environment like so -
public final class MyAppLogic {
@Environment(\.modelContext) private var context
...
...
myClasses.forEach { myClass in
context.insert(myClass)
}
Any suggestions greatly appreciated.
Post not yet marked as solved
Getting a warning from the Xcode compiler about accessing a context outside of a view. It popped up in white text on a purple background, not the usual white on yellow warning color.
The actual warning text is: Accessing Environment's value outside of being installed on a View. This will always read the default value and will not update.
This seems to mean that any datastore access must be done within a view, and isn't possible from the model or some sort of DataManager class. Am I reading this correctly? I'm trying to keep the business logic out of the views. I can do it with everything except the datastore code because of this context issue. Doesn't seem to make sense.
Suggestions greatly appreciated.
Post not yet marked as solved
I have two main models, House and Expense. On the home page I show a list of the three most recent expenses using the following query:
var descriptor = FetchDescriptor<Expense>(predicate: #Predicate { $0.houseID == house.id }, sortBy: [SortDescriptor(\.date, order: .reverse)])
descriptor.fetchLimit = 3
_recentExpenses = Query(descriptor)
I have a NavigationLink that takes you to the full list of expenses:
NavigationLink {
ExpenseListView(house: house)
} label: {
Text("See all")
}
On this page I have a query similar to the previous one, without the fetch limit:
let descriptor = FetchDescriptor<Expense>(
predicate: #Predicate { $0.houseID == house.id}
)
_expenses = Query(descriptor)
The problem is that when I click on the navigation link to go to the expenses page, the app freezes.
I tried passing the expenses array to the second page instead of invoking another query, but this way the view doesn't update when I update the expenses.
Is there a way to solve this problem? Or a way to pass a Binding of the fetched results?
Post not yet marked as solved
I've found a very strange behaviour which looks like a bug. SwiftUI sheet or fullScreenCover do not release objects that were passed to its item: parameter (and to the view builder body by the way, but here is the simplified case).
It works well and memory is releasing on iOS 16 built with both Xcode 14 or 15. (simulators, devices)
Memory is leaking and NOT releasing on iOS 17 built with Xcode 15. (simulator, device 17.0.2)
Any ideas how we can solve this or we have to wait for the bugfix? This is going to be a global memory leak, I am sure most of SwiftUI apps are using classes passed to the sheet or fullScreenCover.
struct SheetView: View {
@State var sheetVM: SheetVM?
var body: some View {
Button {
sheetVM = .init()
} label: {
Text("Navigate")
}
.sheet(item: $sheetVM) { sheetVM in
Color.yellow
}
}
}
final class SheetVM: ObservableObject, Identifiable {
@Published var title: String = "Title"
init() {
print("SheetVM init")
}
deinit {
print("... SheetVM deinit")
}
}
struct SheetView_Previews: PreviewProvider {
static var previews: some View {
SheetView()
}
}
Post not yet marked as solved
Hello Everyone
I'm unable to build my project after updating Xcode 15 get same issue every time and I'm stuck into it give solutions if any one know.
Showing All Errors Only
Build target OneSignalNotificationServiceExtension of project Smartworks with configuration Debug
ld: 11 duplicate symbols
clang: error: linker command failed with exit code 1 (use -v to see invocation)
****11 duplicate symbols
Linker command failed with exit code 1 (use -v to see invocation)****
Post marked as Apple Recommended
I've had a little personal utility running for several versions of macOS that uses
let client = CWWiFiClient.shared()
if let ssid_name = client.interface()?.ssid()
to get the current SSID name and prints it (along with a bunch of other active network details.
With the most recent Sonoma Beta 2 and Xcode beta 2, this always returns nil.
Doing the same thing in a playground works as expected.
Is this a purposeful change or a bug I should file?
Post not yet marked as solved
Hey everyone,
How do I detect that my View is coming into the foreground? The app has been suspended by iOS before, because I closed it (which is fine).
I am running into the strange problem, that .onChange(of: scenePhase) is never triggered on my custom subview. It only works if I attach it to the first view inside the root view.
Some context: My app is iOS 17 and iPhone only.
does work: on TabView() inside ContentView()
ContentView() is the root view of the app.
struct ContentView: View {
@Environment(\.scenePhase) var scenePhase
var body: some View {
TabView {
CustomSubView()
}
.onChange(of: scenePhase) { oldPhase, newPhase in
if newPhase == .active {
// some code, does work
} else if newPhase == .background {
// some code, does work
}
}
}
does not work: on CustomSubView() inside TabView() inside ContentView()
struct CustomSubView: View {
@Environment(\.scenePhase) var scenePhaseCustomSubView
var body: some View {
NavigationStack {
}
.onChange(of: scenePhaseCustomSubView) { oldPhase, newPhase in
if newPhase == .active {
// some code, is not firing for some reason -> use onAppear?
}
else if newPhase == .background {
// some code, does work
}
}
}
}
Thank you for your help
Post not yet marked as solved
After Updating my app to iOS 17.0 I noticed some odd behavior when swiping a detail view away with a parent view that has a toolbar with a ToolbarItem(placement: .bottomBar).
As the user starts a leading swipe gesture to navigate back to the previous view the parent navigation title strangely animates to the center and the leading nav bar button disappears. If the user stops this gesture at any point before completing the swipe they will be stuck in the detail view as the leading nav button has disappeared. This only seems to be an issue if one attempts to swipe back to the parent view and not when the leading nav button is tapped.
The following is the minimum code to reproduce this issue for me. I am testing on a physical device on iOS 17.0 with Xcode Version 15.0 (15A240d).
struct ToolbarIssueView: View {
var body: some View {
NavigationStack {
NavigationLink {
Text("Detail View")
.navigationTitle("Detail")
} label: {
Text("To Detail View")
}
.toolbar {
// This seems to cause strange behavior
ToolbarItem(placement: .bottomBar) {
Text("Bottom Bar Content")
}
}
.navigationTitle("Main")
}
}
}
I understand that this bottom bar could easily be replaced with a .safeAreaInset(edges: .bottom) but I would prefer to use the more standard ToolbarItem(placement: .bottomBar).
If anyone has any fixes for this issue or know what I am missing I would love to hear it!
Post not yet marked as solved
Is it possible to trigger an action in a Swift UI app from an iOS accessibility sound recognition?
Post not yet marked as solved
I am working on an app which I plan to submit to App Store in 2 weeks. Now I have a headache with Array type.
I have the following API design in my app:
class SomeParser {
func getTranslations(_ locale: String) -> [TranslationUnit]? {
// Check if the locale units are already in a cache, if not build a new list
// and return the list
}
}
class MainVC {
func doTranslation() {
var list = parser.getTranslation("en")
// Modify some units in the list.
// How to put it back to cache?
}
}
Now the problem is that since Array is a value type, the modified list is isolated. The only way to reflect the changes into cache is put the modified list back to cache:
translationCache[locale] = modifiedList
But this is counter-intuitive and waste of performance.
Is there anyway to workaround this problem?
Post not yet marked as solved
I am having coding design difficulties with Array in Swift, see this post. So I decided to turn to the old NSMutableArray.
I'd like to know if there are any known problems of this approach. Any pitfalls and known practices?
I am using UIViewController, and I need to know when devices appearance changes. Previously this worked with a delegate function.
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection) // ⚠️
// Update UI
}
Xcode 15 gives us the deprecation warning.
'traitCollectionDidChange' was deprecated in iOS 17.0: Use the trait change registration APIs declared in the UITraitChangeObservable protocol
The new function with the completion block registerForTraitChanges, needs the [UITrait] parameter.
Both of my attempts are failing to compile.
let traits = [UIUserInterfaceStyle.light, UIUserInterfaceStyle.dark]
view.registerForTraitChanges(traits) { _, _ in
// Update UI
}
Cannot convert value of type '[UIUserInterfaceStyle]' to expected argument type '[UITrait]' (aka 'Array')
view.registerForTraitChanges(self.traitCollection.userInterfaceStyle) { _, _ in
// Update UI
}
Cannot convert the value of type 'UIUserInterfaceStyle' to expected argument type '[UITrait]' (aka 'Array')
Please share working code example.
Also, does the completion block guarantee to run on the main thread?
My request call site:
let headers = coordinator.requestHeaders(path: headersPath)
var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: defaultTimeoutInterval)
request.httpMethod = HTTPRequestMethod.get.rawValue
request.allHTTPHeaderFields = headers
let delegate = SessionDelegate(priority: priority, progressHandler: progressHandler)
let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: .main)
let (localUrl, response) = try await session.download(for: request)
let data = try Data(contentsOf: localUrl)
SessionDelegate:
public class SessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDownloadDelegate {
public typealias ProgressHandler = ((_ progress: Double) -> Void)
public var metrics: URLSessionTaskMetrics?
private let priority: TaskPriority
private let progressHandler: ProgressHandler?
//MARK: - Lifecycle
init(priority: TaskPriority, progressHandler: ProgressHandler? = nil) {
self.priority = priority
self.progressHandler = progressHandler
}
//MARK: - URLSessionTaskDelegate
public func urlSession(_ session: URLSession, didCreateTask task: URLSessionTask) {
task.priority = priority.rawValue
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
self.metrics = metrics
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if let progressHandler {
let progress = Progress(totalUnitCount: totalBytesExpectedToSend)
progress.completedUnitCount = totalBytesSent
progressHandler(progress.fractionCompleted)
}
}
//MARK: - URLSessionDownloadDelegate
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { }
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let progressHandler {
let progress = Progress(totalUnitCount: totalBytesExpectedToWrite)
progress.completedUnitCount = totalBytesWritten
progressHandler(progress.fractionCompleted)
}
}
}
For some reason I get delegate callbacks from URLSessionDelegate and URLSessionTaskDelegate but never from URLSessionDownloadDelegate.
I've tried assigning the delegate to the task or the session (or both), but behavior remains the same.
Not sure if related but when I try using background session configuration I crash on let (localUrl, response) = try await session.download(for: request) with the error Completion handler blocks are not supported in background sessions. Use a delegate instead. even though I use the async version of the download task, and assigning delegate to the session, it might point to the reason why none of the delegate functions is getting called (maybe?), but I have no clue why Xcode thinks I'm using completion handler.
Post not yet marked as solved
// here is the code snippet
func generateSignatureWithPEMFile(data: Data, privateKeyPEM: String) -> Data?
{
let privateKeyBIO = BIO_new(BIO_s_mem())
let privateKeyPEMData = privateKeyPEM.data(using: .utf8)
_ = privateKeyPEMData?.withUnsafeBytes { buffer in
BIO_write(privateKeyBIO, buffer.baseAddress, Int32(buffer.count))
}
let privateKey = PEM_read_bio_PrivateKey(privateKeyBIO, nil, nil, nil)
let signature = UnsafeMutablePointer.allocate(capacity: 64)
var signatureLength: UInt32 = 64
let ctx = EVP_MD_CTX_new()
EVP_DigestInit(ctx, EVP_sha256())
_ = data.withUnsafeBytes { buffer in
EVP_DigestUpdate(ctx, buffer.baseAddress, buffer.count)
}
EVP_SignFinal(ctx, signature, &signatureLength, privateKey)
EVP_MD_CTX_free(ctx)
EVP_PKEY_free(privateKey)
BIO_free(privateKeyBIO)
return Data(bytes: signature, count: Int(signatureLength))
}
// usage
let dataToSign = Data(hex: key)!
let stringDataToSign = Data(stringToSign.utf8)
if let signature = generateSignatureWithPEMFile(data: dataToSign, privateKeyPEM: privateKeyPEM) {
let signatureHex = signature.map { String(format: "%02x", $0) }.joined()
print("Signature (Hex): (signatureHex)")
peripheralsConnected!.writeValue(signature, for: characteristic, type: .withResponse)
} else {
print("Failed to generate the signature.")
}
but i am getting 70 bytes or 71 bytes or 72 bytes in the debug console
@eskimo pls help me !! i am stuck on this point from many days, any help will be appreciated, thanks in advance!!
Post not yet marked as solved
UIFontPickerViewController open the window cannot show, before ios17 is workable.
Post not yet marked as solved
Hello, sorry if this is a repost, but I couldn't find an answer anywhere.
I'm french, thus date are displayed dd//mm//yy for us.
on the DatePicker, when the mode .wheels is enabled, i can see the d/m/y.
Now, let's say there are 30 days on the current month and we are currently the 27th of september
The voiceOver will announce "27... 12 elements on the list"
Switching to the month will announce "9... 30 elements on the list"
The correct result should be "27... 30 elements on the list" and "9... 12 elements on the list"
I don't know if it is related but for some reason, even if my phone is set to language french, region France,
the Local.current return en_FR ( and my app support french english language so I was expecting fr_FR)
So I tried to set the local and the accessibility language of the picker to french but the result is the same.
Another problem occur with the date picker set on .inline
Months are displayed in french, voiceOver announce it in french but as soon as I switch to the days it will announce the number in english.
I'tried on a new project with nothing else but the picker and I still have the same results
Are those some bugs or am I missing something ?