Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

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
Aug ’23
Fatal Exception: NSInternalInconsistencyException Failed to create remote render context
Hi I am receiving this error in crashlytics and I am not sure what is going on. Based from the crashlytics report, it is only happening from iOS 16.2 and above. Any tips and hints on this problem would be great. Here is the bug report. Fatal Exception: NSInternalInconsistencyException 0 CoreFoundation         0x9e48 __exceptionPreprocess 1 libobjc.A.dylib        0x178d8 objc_exception_throw 2 Foundation           0x545a88 -[NSMutableDictionary(NSMutableDictionary) initWithContentsOfFile:] 3 UIKitCore           0x6a2724 __UIKIT_DID_NOT_RECEIVE_A_REMOTE_CACONTEXT_FROM_COREANIMATION_INDICATING_A_POSSIBLE_BACKBOARDD_CRASH 4 UIKitCore           0x5260ec __UIKIT_IS_REQUESTING_A_CACONTEXT_FROM_COREANIMATION 5 UIKitCore           0x347ef0 +[_UIContextBinder createContextForBindable:withSubstrate:] 6 UIKitCore           0x347c64 -[_UIContextBinder _contextForBindable:] 7 UIKitCore           0x347b40 -[_UIContextBinder attachBindable:] 8 UIKitCore           0x13ab50 -[UIWindowScene _windowUpdatedVisibility:] 9 UIKitCore           0x206b80 -[UIWindow _updateLayerOrderingAndSetLayerHidden:actionBlock:] 10 UIKitCore           0x20643c -[UIWindow _setHidden:forced:] 11 UIKitCore           0x34608c -[UITextEffectsWindow _commonInitWithOptions:] 12 UIKitCore           0x345fb8 -[UITextEffectsWindow(UIObjectsForPerCanvas) _initWithCanvas:options:] 13 UIKitCore           0x206908 +[_UIObjectPerCanvas objectOfClass:forCanvas:withOptions:createIfNecessary:] 14 UIKitCore           0xf1d6c4 +[UITextEffectsWindow _sharedTextEffectsWindowforWindowScene:allowHosted:forViewService:matchesStatusBarOrientationOnAccess:shouldCreateIfNecessary:] 15 UIKitCore           0xf1d844 +[UITextEffectsWindow sharedTextEffectsWindowForWindowScene:forViewService:] 16 UIKitCore           0x8e39e4 -[UIKeyboardSceneDelegate containerWindowForViewService:] 17 UIKitCore           0x235094 -[UITextSelectionView showInitialCaret] 18 UIKitCore           0x234120 -[UITextSelectionView updateSelectionRects] 19 UIKitCore           0x233754 -[UITextSelectionView updateSelectionRectsIfNeeded] 20 UIKitCore           0x2336e4 __51-[UITextSelectionView deferredUpdateSelectionRects]_block_invoke 21 CoreFoundation         0x91d40 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ 22 CoreFoundation         0x1a290 __CFRunLoopDoObservers 23 CoreFoundation         0x7bb70 __CFRunLoopRun 24 CoreFoundation         0x80ec0 CFRunLoopRunSpecific 25 GraphicsServices        0x1368 GSEventRunModal 26 UIKitCore           0x3a186c -[UIApplication _run] 27 UIKitCore           0x3a14d0 UIApplicationMain 28 MyApp           0x6274 main + 32 (AppDelegate.swift:32) 29 ???              0x1aad76960 (Missing)
4
0
1.1k
Sep ’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
831
Sep ’23
NFCTagReaderSession.PollingOption.pace fails with "Missing required entitlement" error
Hi, I'm developing an app that reads the NFC tags. So far so good, everything worked as expected, the app reads the passports and the IDs, until we encountered the french ID issued after March 2021. My app has the following entitlements: <dict> <key>com.apple.developer.nfc.readersession.formats</key> <array> <string>TAG</string> </array> </dict> And this additional entries in the .plist: <key>NFCReaderUsageDescription</key> <string>NFC usage to scan ID chip</string> ... <key>com.apple.developer.nfc.readersession.iso7816.select-identifiers</key> <array> <string>A0000002471001</string> <string>A0000002472001</string> <string>00000000000000</string> </array> According to an article which I cannot link on this forum because the domain is not permitted, iOS started supporting this specific ID from version 16. When I look at the docs, I can see the .pace polling mode was added. I tried specifying this additional polling mode in my app like so: var pollingOptions: NFCTagReaderSession.PollingOption = [.iso14443] if #available(iOS 16, *) { pollingOptions.insert(.pace) } self.session = NFCTagReaderSession(pollingOption: pollingOptions, delegate: self, queue: nil) But when I try to start the session it gets instantly invalidated with this message: Missing required entitlement. I'm pretty confident the message is misleading and something else is missing somewhere, my bet would be on the .plist entry com.apple.developer.nfc.readersession.iso7816.select-identifiers missing one of the cryptic numbers, but I have no idea where this can be taken from. How do I implement this .pace polling mode, can someone give me some guidance?
1
0
702
3w
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
Jul ’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
Sep ’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
Jan ’24
Button Labels in MenuBarExtra not showing images/icons
As the title suggests, the icons/images in labels are not appearing in the MenuBarExtra Here is the code I'm running: import Combine import SwiftUI class TimerViewModel: ObservableObject { private var assignCancellable: AnyCancellable? = nil @Published var somelist: Array<String> = ["default"] init() { assignCancellable = Timer.publish(every: 5.0, on: .main, in: .default) .autoconnect() .map { String(describing: $0) } .assign(to: \TimerViewModel.somelist[0], on: self) } } @main struct mbe_testingApp: App { @State var clickCount = 0 @ObservedObject var timerOutput = TimerViewModel() var body: some Scene { MenuBarExtra("mbe test", systemImage: "\(clickCount).circle") { Button() { clickCount += 1 print("incremented") } label: { Label("Increment", systemImage: "plus.square.fill") } Button() { if clickCount > 0 { clickCount -= 1 } print("decremented") } label: { Label("Decrement", systemImage: "minus.square.fill") } Button() { print("clicked") } label: { Label(timerOutput.somelist[0], systemImage: "clock") } } } } which results in a menu that looks like: What am I missing to make the label images appear alongside the text on the menu buttons?
1
0
575
Sep ’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
Nov ’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
1w
SwiftUI Timer not working inside Menu bar extra
Hello, I am new to the Swift and the SwiftUI. I want to build a MacOS app for learning purpose. Looks like I am stuck, so looking for some help. The code below does not execute the print statement. Why is the timer not working? What am I missing? Thanks in advance. struct CustomView: View {         let timer = Timer.publish(every: 1, on: .current, in: .common).autoconnect()     private var nums: [String] = ["one", "two"]         var body: some View {         ForEach(nums, id: \.self) {num in             Text(num)         }         .onReceive(timer) { time in // why is this not working?             print("time is \(time)")         }     } } @main struct Writer: App {     var body: some Scene {         MenuBarExtra("Writer util", systemImage: "pencil.line") {             CustomView()         }         .menuBarExtraStyle(.menu)     } }
6
1
1.3k
Oct ’23
iOS Widget not available in Widget Search on iOS 16
We are running into a major issue with building an iOS Widget. iOS Widgets are basically large informational app icons you can pin to your iPhone home screen (What is a widget?). iOS widgets were introduced in iOS 14. We’ve finished building our iOS widget. However, when half of our users attempt to search for our widget after downloading our app, our widget is not showing up in the widget search results. For the other half, it works fine. This seems to be somewhat of a bug from Apple, as it is affects other widget apps (Apple Thread, the problem exists for large widget apps also). It seems like we are having this issue far more, percentage-wise, than other widget apps. I’ve searched through nearly every resource online (StackOverflow, etc.), which is why I’m posting a question now. Things like deleting the app and reinstalling, restarting the phone, etc. have not been a fix either for these problematic users. It doesn't seem to be tied to any iOS version (14, 15, etc.). As I have iOS 15, and it works fine. But, some users with iOS 15 are getting the bug. Has anyone ran into this issue where a widget is not searchable? How did you fix it? Any resources are appreciated as I am at a major blocker right now. Since my app is primarily based on iOS widgets, this makes it basically unusable for certain users.
1
2
750
Oct ’23
NavigationSplitView how to disable the side bar, to make it like the reminder app in iPad?
I want to make it like this How to disable the button that open the side bar, I only need the content and the detail view. I don't need the sidebar view. Below is my code import SwiftUI @available(iOS 16.0, *) struct Screen: View { @ObservedObject var userData = UserData() @State private var isIntroShown = true @State var Itema: Bool = false @State private var showFoodDetail = false @State var rb: Bool = false @State var Setting: Bool = false @State var Recipe: Bool = false @Environment(\.defaultMinListRowHeight) var minRowHeight @Environment(\.colorScheme) var colorScheme @State private var searchText = "" private let adaptiveColumns = [ GridItem(.adaptive(minimum: 170)) ] var columns = Array(repeating: GridItem(.flexible(), spacing: 10), count: 2) var filteredRooms: [Room] { if searchText.isEmpty { return userData.rooms } else { return userData.rooms.filter { room in let foodNames = room.food.map { $0.name.lowercased() } return room.name.lowercased().contains(searchText.lowercased()) || foodNames.contains { $0.contains(searchText.lowercased()) } } } } @State private var columnVisibility = NavigationSplitViewVisibility.doubleColumn var body: some View { NavigationSplitView (columnVisibility: $columnVisibility){ } content: { ScrollView{ GridView() .padding(.horizontal) .padding(.bottom, 20) }.toolbar { ToolbarItem(placement: .bottomBar){ Button(action:{self.Itema = true}) { HStack { Image(systemName: "plus.circle.fill").resizable().frame(width: 20, height: 20).foregroundColor(.white) Text("New Item").foregroundColor(.white).bold() } } .sheet(isPresented: self.$Itema){ NewItem(userData: self.userData) } } ToolbarItem(placement: .bottomBar){ Button(action:{self.rb = true}) { HStack { Text("New Room").foregroundColor(.white) } } .sheet(isPresented: self.$rb){ NewRoom(userData: self.userData) } } ToolbarItem(placement: .navigationBarTrailing){ Button(action:{self.Setting = true}) { HStack { Image(systemName: "gear").foregroundColor(.white) } } .sheet(isPresented: self.$Setting){ NavigationView { NewItem( userData: userData) .navigationBarItems(trailing:Button(action: { self.Setting = false }){ Text("Done") } ) } } } } .background(Color(red: 203/255, green: 237/255, blue: 207/255)) } detail: { ZStack { Text("") } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color(red: 220/255, green: 247/255, blue: 234/255)) } .searchable(text: $searchText) } }
1
1
1.1k
Jul ’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
696
Jul ’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
Sep ’23