Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

Obtaining CPU usage by process
Hi there, I'm working on an app that contains a mini system monitoring utility. I would like to list the top CPU-using processes. As Quinn “The Eskimo!” has repeatedly cautioned, relying on private frameworks is just begging for maintenance effort in the future. Ideally, I want to go through public headers/frameworks. I've gone to great lengths to try to find this information myself, and at this point I'm just struggling. I detail my research below. Any pointers in the right direction would be much appreciated! Attempts Libproc First I looked at libproc. Using proc_pidinfo with PROC_PIDTHREADINFO, I'm able to get each thread of an app, with its associated CPU usage percentage. Summing these, I could get the total for an app. Unfortunately, this has two downsides: Listing a table of processes now takes O(proces_count) rather than just O(process_count), and causes way more syscalls to be made It doesn't work for processes owned by other users. Perhaps running as root could alleviate that, but that would involve making a priviliedged helper akin to the existing sysmond that Activity Monitor.app uses. I'm a little scared of that, because I don't want to put my users at risk. Sysctl Using the keys [CTL_KERN, KERN_PROC, KERN_PROC_PID, someProcessID], I'm able to get a kinfo_proc - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/sysctl.h#L750-L776 instance. Accessing its .kp_proc - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/proc.h#L96-L150.p_pctcpu - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/proc.h#L123 looked really promising, but that value is always zero. Digging deeper, I found the kernel code that fills this struct in (fill_user64_externproc - https://github.com/apple-opensource/xnu/blob/c76cff20e09b8d61688d1c3dfb8cc855cccb93ad/bsd/kern/kern_sysctl.c#L1121-L1168). The assignment of p_pctcpu - https://github.com/apple-opensource/xnu/blob/c76cff20e09b8d61688d1c3dfb8cc855cccb93ad/bsd/kern/kern_sysctl.c#L1149 is in a conditional region, relying on the _PROC_HAS_SCHEDINFO_ flag. Disassembling the kernel on my mac, I could confirm that the assignment of that field never happens (thus _PROC_HAS_SCHEDINFO_ wasn't set during compilation, and the value will always stay zero) Reverse engineering Activity Monitor.app Activity Monitor.app makes proc_info and sysctl system calls, but from looking at the disassembly, it doesn't look like that's where its CPU figures come from. From what I can tell, it's using private functions from /usr/lib/libsysmon.dylib. That's a user library which wraps an XPC connection to sysmond (/usr/libexec/sysmond), allowing you to create requests (sysmon_request_create), add specific attributes you want to retrieve (sysmon_request_add_attribute), and then functions to query that data out (sysmon_row_get_value). Getting the data "striaght from the horses mouth" like this sounds ideal. But unfortunately, the only documentation/usage I can find of sysmond is from bug databases demonstrating a privilege escalation vulnerability lol. There are some partial reverse engineered header files floating around, but they're incomplete, and have the usual fragility/upkeep issues associated with using private APIs. On one hand, I don't want to depend on a private API, because that takes a lot of time to reverse engineer, keep up with changes, etc. On the other, making my own similar privileged helper would be duplicating effort, and expose a bigger attack surface. Needless to say, I have no confidence in being able to make a safer privileged helper than Apple's engineers lol Reverse engineering iStat Menus Looks like they're using proc_pid_rusage - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/libsyscall/wrappers/libproc/libproc.h#L103-L108 . However, I don't know how to convert the cpu_*_time fields of the resulting struct rusage_info_v4 - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/resource.h#L306-L343 to compute a "simple" percentage. Even if I came up with some formula that produces plausible looking results, I have no real guarantee it's correct or equivalent to what Activity Monitor shows.
5
1
5.4k
Jul ’20
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
Entering debugger: Cannot create Swift scratch context (couldn't create a ClangImporter)
similiar to Error when debugging: Cannot creat… | Apple Developer Forums - https://developer.apple.com/forums/thread/651375 Xcode 12 beta 1 po command in de… | Apple Developer Forums - https://developer.apple.com/forums/thread/651157 which do not resolve this issue that I am encountering Description of problem I am seeing an error which prevents using lldb debugger on Swift code/projects. It is seen on any Swift or SwiftUI project that I've tried. This is the error displayed in lldb console when first breakpoint is encountered: Cannot create Swift scratch context (couldn't create a ClangImporter)(lldb)  Xcode Version 12.3 (12C33) macOS Big Sur Intel M1 Troubleshooting I originally thought this was also working on an Intel Mac running Big Sur/Xcode 12.3, but was mistaken. Using my customized shell environment on the following setups, I encounter the same couldn't create a ClangImporter. M1 Mac mini, main account (an "Admin" account) same M1 Mac mini, new "dev" account (an "Admin" account) Intel MBP, main account They are all using an Intel Homebrew install, and my customized shell environment if that provides a clue? I captured some lldb debugging info by putting expr types in ~/.lldbinit but the outputs were basically identical (when discounting scratch file paaths and memory addresses) compared to the "working clean" account log (described below) log enable -f /tmp/lldb-log.txt lldb expr types works in a "clean" user account I created a new, uncustomized "Standard" testuser account on the M1 Mac mini, and launched the same system Xcode.app. There was no longer this error message, and was able to inspect variables at a swift program breakpoint in Swift context, including po symbol. Impact Effectively this makes the debugger in Swift on Xcode projects on my systems essentially unable to inspect Swift contexts' state.
6
0
4.9k
Jan ’21
Xcode 13 typing is delayed / really slow
I just updated Xcode to the newest Version (13.0 13A233). And what I immediately recognized was that when I was typing in a large class (1000 Lines or more) the typing was delayed like 1 or 2 seconds. This makes it really hard to type or even do anything with my project. It works perfectly fine in smaller projects with only 100 Code Lines per File, but it is really hard to type in bigger projects with over 30 files and 3000 Code Lines per File. This always happens when I use Xcode, whether I run the app on a real device or a simulator. Things that could cause the issue in my case: I removed the contents of ~/Library/Developer/Xcode/iOS DeviceSupport, because it took the device previously too long to launch, but I don´t think that this should have an effect on my Xcode typing performance. I would really appreciate any help, because this issue makes my work impossible and really concerns me a lot.
53
3
21k
Oct ’21
XPC, Swift, ObjC, and arrays
I create a protocol that had, among other things: @objc func setList(_: [MyType], withReply: @escaping (Error?) -> Void) The daemon part is in Swift, while the calling part is in Objective-C. Because why not? (Actually, because the calling part has to deal with C++ code, so that's ObjC++; however, I wanted the stronger typing and runtime checking for the daemon part, so I wrote it in Swift.) The ObjC part uses NSArray<MyType*>. I set up an NSXPCConnection link, and create a (synchronous) proxy with the right protocol name. But when I try to do the XPC setList call, I get an error. I assume that's because it doesn't like the signature. (Surely this is logged somewhere? I couldn't find it, if so. 😩) But... if I have a signature of @objc func addItem(_: MyType, withReply: @escaping (Error?) -> Void), then it works. So I assume it's the array. (Oh, I've also tried it without the @objc; the protocol itself is defined as @objc.) I've tried changing to protocol signature to using NSArray, but same thing.
7
0
1.4k
Dec ’21
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
Embedding an xcframework in another xcframework.
Anytime I try to embed my xcframework (which has another xcframework embedded in it) in an iOS app and run it on a device I get this error in the console : dyld[5028]: Library not loaded: @rpath/Calculator.framework/Calculator   Referenced from:... It runs fine on the simulator however. I've tried several suggested solutions; modifying Runpath Search Paths, Framework Search Paths but to no avail. Is there something I'm missing or you can't have nested frameworks for iOS as per this question? If so why does it run on the simulator though.
2
0
1.5k
Apr ’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.7k
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
7.1k
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
9.6k
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.5k
Oct ’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
3.0k
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.6k
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
1.1k
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.6k
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.4k
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.2k
Feb ’23
Swift Async/Await, how to bring asynchronously calculated results back to main thread
I'm relatively new to Swift, and very new to concurrency via Async/Await, so please be patient. 😀 I'm having a hard time comprehending how to do complex operations asynchronously in background threads, and then in turn bring the results back to the main thread. I'm getting various errors along the lines of "Mutation of captured var 'personName' in concurrently-executing". I've paired the issue down as simply as possible as follows, and you'll see where the compiler gives the error message. I'd appreciate any advice on how to evolve my mental model to make this work. Thanks! Bruce import Foundation actor Person {     var myName = "Thomas Jefferson"     var name: String {         get {             return myName         }     } } func main() {     let person = Person()     var personName: String     print("start")     let nameTask = Task {         return await person.name     }     Task {         do {             personName = try await nameTask.result.get()             // Error: Mutation of captured var 'personName' in concurrently-executing code         } catch {             print("error!!!")         }     }     print("The person's name is \(personName)") } RunLoop.main.run() main()
4
0
4.0k
Mar ’23
Actor URLSession Warning?
Non-sendable type '(any URLSessionTaskDelegate)?' exiting actor-isolated context in call to non-isolated instance method 'data(from:delegate:)' cannot cross actor boundary Please help, I am 1000% stuck on this issue in particular. Using strict asynchronous warnings, how can I make this work without warning? I can convert NetworkManager into a struct, but I prefer to keep it as an actor so that it is Sendable by default.
4
0
2.3k
Apr ’23