Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

Xcode 15 Beta Swift/C++ Interop with C++20
I have a C++ project that produces a lot of libraries that require C++20. I have tried to set the requirement for that in the module.modulemap like so (for example): module cxx_library { requires cplusplus20 header "library.h" link "CXXLibrary" } This seems to be correct per the clang documentation: https://clang.llvm.org/docs/Modules.html#requires-declaration However I cannot figure out how to get cmd+click on the imported module in my sample swift file to work with this. For one, Xcode seems to refuse to even import my module when it requires C++20. How do I tell Xcode that all of my C++/ObjectiveC++ requires C++20? The compiler default is C++14, but it's not clear how to properly change that so that I can import a C++20-enabled clang module into some sample swift projects to try out the new interior features. If I remove the 20 from my requires statement, and just use my code as-is, It always complains in the UI that: Couldn't Generate Swift Representation Error (from SourceKit): "Could not load module: cxx_library (could not build Objective-C module 'cxx_library', unknown type name 'char8_t')" Which is very frustrating. When I compile with CMake, I can just set this: add_executable(E E.swift) target_compile_options(E PRIVATE -cxx-interoperability-mode=default SHELL:-Xcc SHELL:-std=c++20) target_link_libraries(E PRIVATE cxx_library) And swiftc compiles the code with no issue. I have uploaded a minimized version of my code as a fork of a project by compnerd on GitHub here: https://github.com/ADKaster/swift-cmake-examples/tree/main/Interop The project builds just fine with cmake -S Interop -B build -GNinja cmake --build build But by creating an Xcode project from it: cmake -S Interop -B build-xcode -GXcode and then opening build-xcode/P.xcodeproj in Xcode 15 Beta, and trying to cmd-click on import cxx_library in E.swift does not work.
6
0
1.4k
Aug ’23
Swift Playgrounds: Unable to Resolve Package ‘Graphics’ and ‘unzip’ Executable Not Found Error
When I import a package in Swift Playgrounds on my iPad, I receive the following error: This package interactions with libgit2, and it don’t have any release in the origin repository, so I find a existing fork which have release. Playgrounds version: 4.3.1(1727.53) Is it means that I install a software that supports unzip on iPad?
0
0
664
Aug ’23
Find the name of a CNContact's group (CNGroupName)
So I only recently uncovered the Contacts Framework through this video: https://youtu.be/sHKir2ZMk5Q. As such I'm not yet accustomed to the API. Basically my main problem is that I can't seem to find a way to access the name of the group a CNContact is in. The only support I can find is in Apple's own documentation, which isn't very helpful. if someone could point me in the right direction towards how to print the group name, I would be very grateful. My code is below, Cheers // ModelData.swift // B-Day import Foundation import Contacts import SwiftUI struct Contact: Identifiable { let id = UUID() let category: String let firstName: String let lastName: String let birthday: DateComponents? } func fetchAllContacts() async -> [Contact] { var contacts = [Contact]() let store = CNContactStore() let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactBirthdayKey, CNContactIdentifierKey, CNGroupNameKey] as [CNKeyDescriptor] let fetchRequest = CNContactFetchRequest (keysToFetch: keys) do { try store.enumerateContacts(with: fetchRequest, usingBlock: { contact, result in //this should print the name of the contact's group print(contact.groupName) contacts.append(Contact(category: contact.groupName, firstName: contact.givenName, lastName: contact.familyName, birthday: contact.birthday)) }) } catch { print("Error") } return contacts }
1
0
693
Aug ’23
Keyboard extension input auto enter
Hi all, So im develop a keyboard extension to have it custom for my distinct host app. The keyboard are connect with hardware barcode scanner. I have problem to auto 'send' the form when the barcode read. So, if I have other string (barcode) combine with the ("\r"), this will not trigger the auto send. func performBarcodeScan(barcode: String, scanner: String) { textDocumentProxy.insertText(barcode+"\r") } But, I tried with this situation where i already type some string input in the field and have only ("\r") as below, that will work func performBarcodeScan(barcode: String, scanner: String) { textDocumentProxy.insertText("\r") } have the insertText twice to separate the string also not work. I hope anyone can help with this as i have been stuck forrr a longgggg time. Thanks in advanced!
0
0
323
Aug ’23
Failed to produce diagnostic for expression;
Hey I am getting this in my code, I'm a new coder and I need help fixing this, here is my code, please tell me my errors! Thank You! import SwiftUI enum Emoji: String{ case 😀,😝,🤨,🎉 } struct ContentView: View { @State var selection: Emoji = .🎉 var body: some View { VStack { Text(selection.rawValue) .font(.system(size: 150)) Picker("Select Emoji", selection: $selection) { ForEach(Emoji.allCases, id: \.self){ emoji in Text(emoji.rawValue) } } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
1
0
342
Aug ’23
Get Wordpress posts
Hello, I would like to display my Wordpress posts in my app. Unfortunately, I always have the problem via the Wordpress API that the page remains completely white. Finally, I tried it via FeedKit, here I get to the point where he can display and load the posts, but only a certain part. Like a preview. But it should show everything in the DetailView. What is the best way to do that? Thanks! Kind Regards Max
2
0
305
Aug ’23
Loading NSImage from icns file takes very long for Visual Studio Code icon
I am trying to load an app icon from an icns file. I am using the following code: guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.microsoft.VSCode") else { return nil } let icon = NSWorkspace.shared.icon(forFile: url.path) This seems to work very fine for all apps that I tested. All of them? No. Loading the icon for Visual Studio Code takes 4-5 seconds. Are there any other, faster methods? I also tried to use NSImage(contentsOfFile: url.path) which also takes very long. I have uploaded the icns file here: https://sascha-simon.com/Code.icns How can this behavior be explained?
4
0
763
Aug ’23
when my custom alert show, navigation bar back button still can press
it's really a simple demo here, when I use NavigationLink destination, go to ContentView3(),i show a custom alert, when it show up, the navigation back button still work.what can I do, when my alert show , and set the back button clickable to false?(the alert must be a custom one, cannot use system .alert) import SwiftUI struct ContentView: View { @State var isActive : Bool = false var body: some View { NavigationView { NavigationLink( destination: ContentView2(rootIsActive: self.$isActive), isActive: self.$isActive ) { Text("Hello, World!") } .isDetailLink(false) .navigationBarTitle("Root") }.navigationViewStyle(.stack) } } struct ContentView2: View { @Binding var rootIsActive : Bool var body: some View { NavigationLink(destination: ContentView3(shouldPopToRootView: self.$rootIsActive)) { Text("Hello, World #2!") } .isDetailLink(false) .navigationBarTitle("Two") } } struct ContentView3: View { @Binding var shouldPopToRootView : Bool @State var showTip = false var body: some View { ZStack { VStack { Text("Hello, World #3!") Button (action: { self.shouldPopToRootView = false } ) { Text("Pop to root") } Button (action: { self.showTip.toggle() } ) { Text("show tip") } } // when alert show up, the back button still work, what can I do stop it? let the back button clickable to false? if showTip { TipAlert(isPresented: $showTip, tip: "123445", negative: "", positive: "OK") { } } } .navigationBarTitle("Three") } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } struct TipAlert: View { @Binding var isPresented: Bool let tip: String let negative: String let positive: String let action: (() -> Void) var body: some View { ZStack { Color.gray.edgesIgnoringSafeArea(.all).opacity(0.75) VStack(spacing: 10) { Text(tip) .font(.system(size: kFrontSize_18)) .foregroundColor(.black) HStack (alignment: .center, spacing: 20){ Spacer() if !negative.isEmpty { Button { isPresented.toggle() } label: { Text(negative) .font(.system(size: kFrontSize_15)) .padding(.horizontal, 12) .padding(.vertical, 8) .frame(minWidth: 55) .foregroundColor(.white) .clipShape(RoundedRectangle(cornerRadius: 5)) } } Button { action() isPresented.toggle() } label: { Text(positive) .font(.system(size: kFrontSize_15)) .padding(.horizontal, 12) .padding(.vertical, 8) .frame(minWidth: 55) .foregroundColor(.white) .clipShape(RoundedRectangle(cornerRadius: 5)) } Spacer() } } .padding(10) .background(.white) .frame( width: 340 ) .cornerRadius(5) } } }
0
0
309
Aug ’23
Passwordless single sign on using SFSafariViewController in swift
0 I integrate with safriService (SFSafariViewController) to log in through a single sign-on password, the problem was the first time I log in using SFSafariViewController but the authentication follow not complete the first time so the safari browser still appear & can not direct into my app after authentication follow to become a success, another behavior is when I login again the authentication follow work fine & get the token then directed into my app fine so the main problem is the first time I login SFSafariViewController does not catch the user auth if let url = URL(string: "url") { let safariVC = SFSafariViewController(url: url) safariVC.delegate = self safariVC.dismissButtonStyle = .done present(safariVC, animated: true, completion: nil) } extension DouWebViewVC: SFSafariViewControllerDelegate { func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) { if didLoadSuccessfully { print("didLoadSuccessfully") // Do something with the URL here } } //initialLoadDidRedirectTo func safariViewController(_ controller: SFSafariViewController, initialLoadDidRedirectTo requestUrl: URL) { let absoluteUrl = requestUrl.absoluteString print("requestUrl(requestUrl)") } func safariViewControllerDidFinish(_ controller: SFSafariViewController) { print("safariViewControllerDidFinish") } }
0
0
605
Aug ’23
[Xcode 15.0 beta 5] [macOS Sonoma beta 4] SwiftData, symbol not found.
Hey everyone, I'm trying to add SwiftData to my project and I have the following model: @Model final class Folder { @Attribute(.unique) let id: UUID var name: String init(name: String) { self.id = UUID() self.name = name } } Since adding this model, I am unable to launch my app. I receive the following error in the console: Symbol not found: _$s9SwiftData014DefaultBackingB0C3forACyxGxm_tcfC What would be causing my project to longer build after adding SwiftData?
1
0
591
Aug ’23
Xcode 15 beta 6: is xrOS no longer considered as iOS?
In Xcode 15 beta 6, I found that when building visionOS apps, #if os(iOS) is no longer considered part of the project. This behavior is different from beta 1 to beta 5. Is this intentional? This change has caused third-party dependencies that use #if os(iOS) and have not yet explicitly supported visionOS to fail to compile. Is there a way to switch back to the old behavior? After all, requiring all third-party dependencies to explicitly support visionOS is quite difficult.
3
0
1.1k
Aug ’23
Updating displayed data generates reentrant warning
I have a program that displays data in a table in the main view. It gets this data by running a C API Select statement. On the main view there is also a button which allows me to change the sort order to descending. To do so, this button calls the same function initially called to display data but with a different order by string for the Select statement. Selecting the button causes the data to be displayed in descending order and it is very fast. Unfortunately selecting the button also causes a warning to be displayed in Xcode "Application performed a reentrant operation in its NSTableView delegate". I do not understand what to do to resolve the issue. Any assistance will be appreciated. Below is the Context View and the View Model. The QueryDatabase function called in the view model is just the C api calls including Prepare, Step in a while loop and Finalize. If it would be helpful I can add it. // Main View: struct ContentView: View { @ObservedObject var vm: SQLiteViewModel = SQLiteViewModel() var body: some View { if vm.loadingData == true { ProgressView() .task { vm.GetSQLData(fundName: "Fund1", numYears: 1, sortOrder: "main.TimeStamp ASC") } } else { HStack { Spacer() .frame(width: 135, height: 200, alignment: .center) Table(vm.fundData) { TableColumn("Fund") { record in Text(record.fundName) .frame(width: 60, height: 15, alignment: .center) } .width(60) TableColumn("Date") { record in Text(sqlDateFormatter.string(from: record.timeStamp)) .frame(width: 120, height: 15, alignment: .center) } .width(120) TableColumn("Close") { record in Text(String(format: "$%.2f", record.close)) .frame(width: 65, height: 15, alignment: .trailing) } .width(65) } // end table .font(.system(size: 14, weight: .regular, design: .monospaced)) .frame(width: 330, height: 565, alignment: .center) Spacer() .frame(width: 30, height: 30, alignment: .center) VStack { Button(action: { vm.GetSQLData(fundName: "Fund1", numYears: 1, sortOrder: "main.TimeStamp DESC") }) { Text("Date Descending") } // end button .frame(width: 140) } // end v stack .font(.system(size: 12, weight: .regular, design: .monospaced)) } // end horizontal stack .frame(width: 600, height: 600, alignment: .center) } // end else statement } // end view } // View Model: class SQLiteViewModel: ObservableObject { var db: OpaquePointer? @Published var fundData: [TradingDay] = [] @Published var loadingData: Bool = true init() { db = OpenDatabase() } func GetSQLData(fundName: String, numYears: Int, sortOrder: String) { DispatchQueue.main.async { self.fundData = QueryDatabase(db: self.db, fundName: fundName, numYears: numYears, sortOrder: sortOrder) self.loadingData = false } } }
1
0
465
Aug ’23
For a custom Sequence protocol, but index don't change, but use while index change. why?
struct BoxedFibonacciSequence: Sequence, IteratorProtocol { typealias Element = Int var currentIndex = 0 mutating func next() -> Int? { defer { currentIndex += 1 } return loadFibNumber(at: currentIndex) } func makeIterator() -> Self { return self } } func loadFibNumber(at index: Int) -> Int { return fibNumber(at: index) } var box = BoxedFibonacciSequence() for v in box { print("for index",box.currentIndex) if v < 20 { } else { break } } let fib = BoxedFibonacciSequence() var iter = fib.makeIterator() while let v = iter.next() { print("while index",iter.currentIndex) if v < 20 { } else { break } } why use for index always 0, but while index is normal? I'm confused.
0
0
174
Aug ’23
Custom Sequence, use `for` index don't change, but `while` is normal. why?
struct BoxedFibonacciSequence: Sequence, IteratorProtocol { typealias Element = Int var currentIndex = 0 mutating func next() -> Int? { defer { currentIndex += 1 } return loadFibNumber(at: currentIndex) } func makeIterator() -> Self { return self } } func loadFibNumber(at index: Int) -> Int { return fibNumber(at: index) } var box = BoxedFibonacciSequence() for v in box { print("for index",box.currentIndex) if v < 20 { } else { break } } let fib = BoxedFibonacciSequence() var iter = fib.makeIterator() while let v = iter.next() { print("while index",iter.currentIndex) if v < 20 { } else { break } } //out put: //for index 0 //for index 0 //for index 0 //for index 0 //for index 0 //for index 0 //for index 0 //for index 0 //for index 0 //while index 1 //while index 2 //while index 3 //while index 4 //while index 5 //while index 6 //while index 7 //while index 8 //while index 9
1
0
207
Aug ’23
Open Safari In Front of User
Hello, when calling the Swift openURL() method, Safari is opening at the origin (below the camera) instead of in front of the user. If I open Safari via the home page, it opens in front of the user. Seems like a bug with Vision OS. Is there something I am missing, and can others replicate the problem? if let url = URL(string: myURL){ openURL(url) }
0
0
311
Aug ’23
Sometimes I cannot scan for Beacon or BLE in the background on iPhone
Hello. I am trying to create an app that detects the beacon and makes a BLE connection when the beacon is turned on while the iPhone is in sleep mode, without the app being on the app switcher. However, there are often times when beacons cannot be detected or BLE connections cannot be made. From what I've found, it's because iOS limits beacon/BLE scanning for security reasons. I know it's impossible, but is there any way to remove this restriction on scanning? If you can't, we would like to know when iOS places restrictions on scanning. If you can't, then we would like to know when iOS places restrictions on scanning and when those restrictions are lifted. Thank you very much. Development Environment: iPhone8 (iOS 13.7), iPhone13(iOS 16.0.3), macOS Monterey, MacBook Pro 2020(Intel Core i5), Xcode 14.2
1
0
493
Aug ’23
How to call swiftdata .fetch inside the Init of a SwiftUI View?
I have a list of swiftdata objects I want to fetch and show in a swift UI list. My problem is the swiftdata object in my DB is not the object I directly want to use in my view. I want to map it to a different viewModel and use that which makes my life wayyy easier. problem is every single example I see online of swift data, just uses the magic @Query operator to get their data, and then directly show it on the UI. What's the best way for me to load the data on initialization but map it to a different type? I've tried this, but it just crashes. init() { do { modelContainer = try ModelContainer(for: MY_DATA_CLASS.self) } catch { fatalError("Could not initialize ModelContainer") } let serverList = FetchDescriptor<MY_DATA_CLASS>( sortBy: [SortDescriptor(\.displayOrder)] ) do { viewModels = try modelContext.fetch(serverList).map { ViewModel(server: $0) } } catch { print(" WHAT THE HECKKK: " + error.localizedDescription) } } NSFetchRequest could not locate an NSEntityDescription for entity name .... any suggestions greatly appreciated. Using @query works fine so I know the rest of the DB is setup correctly.
2
0
1.5k
Aug ’23
Using discardingTaskGroup to limit concurrent tasks?
I'm having trouble understanding the use case for discardingTaskGroup. In my app, I want to submit 10 concurrent image upload requests; usually, I'd just fire off 10 unstructured Task {} instances (I'm assuming this is fine) for image in images { Task { do { try await uploadImage(item: item, image: image) } catch { // Handle any errors } } } But then I thought I'd actually like to have a max of ~3 uploads concurrently, where I would prioritize the images that appear to the user earlier first. I know using group.next() in a taskGroup we can await on previous results and add tasks as required. But my task does not return data, rather it performs an action. So, it seems like the new discardingTaskGroup could be a useful API. Task { do { try await withThrowingDiscardingTaskGroup { group in for image in images { group.addTask { try await uploadImage(item: item, image: image) } } } } catch { // Handle any errors } } How can I convert this discarding task group code to only include a max of n tasks running concurrently? And is this even a reasonable use of the new API to begin with? Best, T
1
0
1k
Aug ’23