Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

WeatherKit Swift / REST mismatch? daytimeForecast and overnightForecast not available via Swift?
I am able to obtain daily forecasts via the REST API which include the daytimeForecast and overnightForecast records with their respective properties like cloudCover. So far I have failed to access them via the Swift API: forecast.daytimeForecast.cloudCover results in: "Value of type 'DayWeather' has no member 'daytimeForecast'". But if I print() the DayWeather objects, these members are actually printed with all their properties. Is there a way to get them I am overlooking?
2
0
1.6k
Dec ’22
Developer Mode setting missing on iPhone
This is the first time I’ve tried to run an Xcode app on my iPhone. To do this, the iPhone must have “Developer Mode” enabled but this settings was not visible on my iPhone. I searched the blog and did not find a suitable solution. Eventually, I got it working so wanted to publish my findings. I am documenting this after trying many things so I am not 100% sure of the magic formula, but “I think” this is what is needed. PROBLEM iPhone -> Settings -> Privacy & Security -> Developer Mode (NOT VISIBLE) ENVIRONMENT iPhone 12 Pro Max running IOS 16.2 MacBook Pro running macOS 12.5.1 Xcode 14.2 CONNECT IPHONE TO MAC (via USB cable) CHECK DEVICE STATUS (in Xcode) Select menu Window -> Devices and Simulators You should see your iPhone but it will show warnings/issues. (e.g. device not in Developer Mode) ADD APPLE ID (in Xcode)  Open your app project in Xcode Select menu Xcode -> Preferences Select Accounts tab Add your Apple ID (It will be listed as a “Personal Team”) SELECT IPHONE AS DESTINATION (in Xcode)  Select menu Product -> Destination -> Choose Destination In the “IOS Device” section, select your iPhone as the destination (NOTE: After doing this, the “Developer Mode” setting was available on my iPhone) iPhone -> Settings -> Privacy & Security -> Developer Mode (Now visible) SELECT DEVELOPER MODE (on iPhone) Settings -> Privacy & Security -> Developer Mode (ENABLE) SELECT APPLE ID AS TEAM (in Xcode)  Select your project in the Project Navigator Select the project in the TARGETS section Select “Signing & Capabilities” tab In the “Signing” section, select the Team as your Apple ID (you previously entered) After this, I had an error and need to modify the “Bundle Identifier” to make it unique. I just added some numbers to the end and it worked. CHECK. DEVICE STATUS (in Xcode)  Select menu Window -> Devices and Simulators This time, your iPhone should appear without any warnings/issues. LOAD APP ONTO IPHONE (in Xcode)  Hit the arrow in Xcode to Start the active scheme. (The App will be loaded onto your iPhone.) RUN APP (on iPhone) Try running the app and the iPhone will not allow it since you have not authorized apps from this developer. Goto Settings -> General -> VPN & Device Management Authorize your Apple ID to run apps on this phone. You should now be able to run the app without issue.
3
0
9.1k
Dec ’22
await UIApplication.shared.beginBackgroundTask inside an async method
Looking for tips here. I've got Swift Concurrency Checking set to Complete - so I'm seeing interesting warnings that I'd like to hear what the proper way to fix this is. I've got an async method that I'm using in a variety of places that I need to specify is a task that needs to complete even if the user goes into the background. It can take 2-60 seconds depending on DNS/network and server responses. func checkRoutineDepartures() async {         var bgTaskId: UIBackgroundTaskIdentifier = .invalid         bgTaskId = await UIApplication.shared.beginBackgroundTask(withName: "checkRoutineDepartures") {             UIApplication.shared.endBackgroundTask(bgTaskId)             bgTaskId = .invalid         } With the complete option, I get a warning Non-sendable type '(() -> Void)?' passed in call to main actor-isolated function cannot cross actor boundary on the completion handler and then on the endBackgroundTask line I get Call to main actor-isolated instance method 'endBackgroundTask' in a synchronous nonisolated context; this is an error in Swift 6 In the docs for both of these, it says I can call them This method can be safely called on a non-main thread. So it seems to me like the headers are incorrectly marking the entire class as Main Actor and missing these methods, or I'm doing something wrong.
2
4
932
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.4k
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.1k
Jan ’23
cannot access music file from Music app on iPad
Hi I have this piece of code in my app that is supposed to open up a file from Music(old iTunes) app and play. But I get 'Attempted to register account monitor for types client is not authorized to access "com.apple.account.iTunesStore". Any suggests how to fix this. What entitlements do I need to set? Code and error logs are below code-block ``` func showiPOD() {           let mediaPicker: MPMediaPickerController = MPMediaPickerController.self(mediaTypes:MPMediaType.anyAudio)     mediaPicker.delegate = self as MPMediaPickerControllerDelegate     mediaPicker.allowsPickingMultipleItems = false     mediaPicker.showsCloudItems = true //show from iCloud as well.. needs to be tested     self.present(mediaPicker, animated: true, completion: nil)   } 2023-01-24 09:31:22.018992-0800 Smart Practice[526:16253] [Entitlements] MSVEntitlementUtilities - Process Smart Practice PID[526] - Group: (null) - Entitlement: com.apple.accounts.appleaccount.fullaccess - Entitled: NO - Error: (null) 2023-01-24 09:31:22.022520-0800 Smart Practice[526:16253] [core] Attempted to register account monitor for types client is not authorized to access: {(   "com.apple.account.iTunesStore" )} ```language code-block
5
3
2.1k
Jan ’23
UIPasteboard permission dialog disappear immediately if paste from universal clipboard
I was trying to copy and paste from my mac laptop to iPhone while using UIPasteboard. The permission dialog popped up for less than 1 second and disappear. If using UIPasteboard again, the dialog will stay. If copying locally without using universal clipboard, the permission dialog will stay. I made a workaround to display the permission dialog again after the first dialog disappears: if UIPasteboard.general.hasStrings {                   // A workaround for the issue that the permission dialog disappear     // immediately while using universal clipboard if #available(iOS 16, *) { if let str = UIPasteboard.general.string?.prefix(8) {          self.regCodeTextFieldModel.text = String(str)         }     }                        if let str = UIPasteboard.general.string?.prefix(8) {       self.regCodeTextFieldModel.text = String(str)      } } Does anyone have a better solution to this issue?
1
1
830
Jan ’23
Swift iOS iPadOS app for Smartcard Token PIV using CryptoTokenKit
Please excuse my lack of understanding of what are probably fundamental concepts in iOS/iPadOS development but I have searched far and wide for documentation and haven't had much luck so far. I am not sure that what I want to do is even possible with an iPad iPadOS app. Goals: Develop a Swift iPadOS app that can digitally sign a file using a PIV SmartCard/Token (Personal Identity Verification Card): Insert a PIV SmartCard/Token (such as a Yubikey 5Ci) into the lightning port of an iPadOS device iPad (NOT MacOS) Interface with the SmartCard/Token to access the user's PIV certificate/signature and "use it" to sign a file Question 1: How to get the PIV Certificate from SmartCard/Token/Yubikey into iPadOS keychain?   * Do we need to get the PIV certificate into the iOS keychain? Is there another way to interact with a SmartCard directly?   * This should prompt the user for their PIN? Question 2: How to get our Swift app to hook into the event that the SmartCard/Token is inserted into the device and then interface with the user's certificate?   * When is the user prompted to enter their PIN for SmartCard/Token/Yubikey?   * Do we need to use CyrptoTokenKit to interface with a smartcard inserted into the lightning port of an iOS device?
10
1
2.3k
Feb ’23
Understanding the warning and how to fix it: Non-sendable cannot cross actor boundary
Hi all, I'm testing the first beta for iOS 16.4 and Xcode 14.3 and I'm getting these warnings that I kind of understand, but I don't know and I haven't found how to solve them. For example this code that is just a simplified example: @MainActor class ATextModel: ObservableObject {     @Published private(set) var record: CKRecord?     func getData() async {         let database = CKContainer.default().publicCloudDatabase         let query = CKQuery(recordType: "Test", predicate: NSPredicate(value: true))         do {             let results = try await database.records(matching: query)             self.record = try results.matchResults.first?.1.get()         } catch {             print("Error: \(error.localizedDescription)")         }     } } Is giving me 2 warnings: Non-sendable type '(matchResults: [(CKRecord.ID, Result<CKRecord, any Error>)], queryCursor: CKQueryOperation.Cursor?)' returned by call from main actor-isolated context to non-isolated instance method 'records(matching:inZoneWith:desiredKeys:resultsLimit:)' cannot cross actor boundary Non-sendable type 'CKQuery' exiting main actor-isolated context in call to non-isolated instance method 'records(matching:inZoneWith:desiredKeys:resultsLimit:)' cannot cross actor boundary Does someone has a hint on how I should do this now? This might be just an error in the beta, but I don't really think that.
5
3
5.9k
Feb ’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
1k
Feb ’23
Unknown Insta-Crash With NO_CRASH_STACK
Hi! We've recently released an usual app-update, but suddenly got a bunch of crashes in App Store Connect and almost none in Firebase Crashlytics. According to customer support, for some users the app insta-crashes. A white screen appears for a flash and then they're returned to the home screen. The app always insta-crashes, only a reinstall fixes it. It makes sense while Crashlytics isn't reporting any crashes, because it doesn't even get a chance to run and upload the crash reports to their server. The Xcode organizer does show a bunch of crashes, but with no stack trace. It just says MyApp: NO_CRASH_STACK. Looking at the explicit 'xccrashpoint' in Finder reveals a couple of crash reports, that I've attached, but they're not that useful. As far as I can tell, the app crashes while it's trying to load the Swift core, that's embedded in the app, but I'm not sure why that would cause a crash. Maybe it was supposed to use the library embedded in iOS (/usr/lib/swift/libswiftCore.dylib)? Any help would be greatly appreciated 🍺! report.crash
3
0
1.4k
Mar ’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
3.1k
Mar ’23
Toobar Items Not Clickable Mac Catalyst Tutorial
Hi, I am giving Mac Catalyst a try and Apple has provided a tutorial for that but it seems a bit buggy. In the tutorial https://developer.apple.com/tutorials/mac-catalyst/updating-the-app-icon there is the completed Catalyst xcode project (in the Complete folder). I downloaded and ran the completed project in Xcode Version 14.2, using my Mac to run it in simulation. The toolbar at the top of the window has the icons for edit and favorite but they appear to be greyed out and don't do anything when clicked. The selectors are set properly for their actions in the ToolBarDelegate file but nothing happens when I select a recipe, which it appears you have to do in order for those buttons to work, then try to click either one of those items Those buttons never appear to be enabled at all even though I have selected a recipe and the coding seems correct. I am confused as to why this doesn't work. The NSSharingServicePickerToolbarItem is enabled and seems to work. I didn't post any code since the project can be readily downloaded and viewed/run. Any help is much appreciated
1
0
694
Apr ’23
Problem: App Cannot be installed because its integrity could not be verified
Hi, I am currently coding an App using Xcode (Swift). For installing my app on devices I make us of over the air installation (OTAI). When ever I want to test it on my own device and I download & install it there is no problem at all. But when I try to install it on a third IOS device, the error "App Cannot be installed because its integrity could not be verified" appears. In general, I want the App to be installable through OTAI. It will not be listed on the AppStore. When archiving the app on Xcode, I use following options: Ad Hoc Additional Options: ✅ Include manifest for over-the-air-installation My URLs Automatically manage signing and then I just export and upload the IPA on https://installonair.com. Thank you for helping me! :)
1
1
584
Apr ’23
FileProvider Extension not working when code signed
My project has a base app which is manually signed, inside I have a FileProvider parent app and extension. When things works elegantly in Xcode debug build when I run FP App. But, when I package it, the FileProvider can't mount, fails with a generic error on parent app (Error Domain=NSFileProviderErrorDomain Code=-2001 "The application cannot be used right now." UserInfo={NSLocalizedDescription=The application cannot be used right now.} Another generic error in FileProvider demon fileproviderd(488) deny(1) file-read-data /Applications/XYZ.app/Contents/Resources/FileFP.app How to solve this?
2
0
1.4k
Apr ’23