Dive into the world of programming languages used for app development.

All subtopics

Post

Replies

Boosts

Views

Activity

Jump to Definition on Symbols in a Swift Framework's Gigantic Generated "Header"?
So I'm looking inside the documentation for TipKit, which ~1400 lines in a single file of documentation. If I right click a symbol there is no "Jump to Definition" in the context menu. Steps to reproduce: Navigate to TipKit generated "header". Right click a symbol like Tip (highlighted in bold): public struct AnyTip : Tip 3rd step) No Jump to Definition menu item appears in the context menu. Is this intentional behavior?
2
0
439
Oct ’23
NSView.clipsToBounds not available
Xcode 15 and Sonoma expose the property NSView.clipsToBounds. On Sonoma I need to set this property to TRUE and this is working well. However, for reasons, I also need to compile my macOS project with Xcode 13 and Xcode 14. I am having difficulty figuring out the Swift #available and @available directives to allow this. No matter how I wrap the self.clipsToBounds = true statement, on these earlier versions of Xcode I get a Swift error telling me that clipsToBounds cannot be found. Any help would be appreciated.
4
0
840
Oct ’23
I need the information about the access-points/devices of the connected Wifi network
Hey, I need the information about the access-points/devices of the connected Wifi network, I repeat only of the **connected Wifi network ** My use caes is about the indoor positioning of a user connect the network and for that I need the information of all the access points (e.g. ssid, bssid, rssi etc.) but till now I am unable to find any starting point/solution for this. Any help regarding this will be highly appreciated. Regards, Aqeel Ahmed
8
0
889
Oct ’23
How can I get devices connected to the same wifi network?
I need to get all devices names which are connected to same wifi. I tried NetServiceBrowser, in netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) function I get some devices name like Macbook or iPad with search service type of browser.searchForServices(ofType: "_services._dns-sd._udp.", inDomain: "local.") But in this service type I cant get iPhones. I'm not sure if this is the right way, which framework should I use to accomplish this? Am I on the right track? What permits do I need to get? I need your help. Best regards.
3
1
831
Oct ’23
Passing locale into a RegexBuilder as a parameter
I am building a tokeniser, and would like to hold this as a struct, passing in a locale during initiation. Here's the gist of what I would want to write: struct Tokeniser { private let locale: Locale private let integerRegex: Regex init(locale: Locale) { self.locale: Locale self.integerRegex = Regex { Capture { .localizedInteger(locale: locale) } transform: { Token.number($0) } } } func parse(text: String) -> Token { if let match = try integerRegex.firstMatch(in: text) { //... other code here } } \\...other code here } As Regex is generic the compiler suggests to set the integerRegex's type to Regex<Any>, but this triggers another set of compiler issues that I have not been able to figure out what the type should be. So then I tried to write something like this (inspired by SwiftUI): var integerRegex: some Regex { Capture { .localizedInteger(locale: locale) } transform: { Token.number($0) } } But again, the compiler prompts me to enter Regex. The only way I have to be able to get the struct to compiler is to create lazy variables, which then have the side effect that I have to mark my functions as mutable, which have downstream issues when they are called from with SwiftUI structs. lazy var integerRegex = Regex { Capture { .localizedInteger(locale: locale) } } mutating func parse(text: String) -> Token { if let match = try integerRegex.firstMatch(in: text) { } } How can I code this?
0
0
308
Oct ’23
Shell script which uses Swift and CryptoKit underneath doesn't work after updating to Xcode 15 and MacOS Sonoma
Hi, I'm having some trouble running a shell script that worked before I updated the Xcode and my MacOS. This is probably connected to the command line tools which were updated with these upgrades. I can't switch to an older version of the command line tools to verify this theory tho... The script uses CryptoKit to decrypt some data which was encrypted using a SymmetricKey. The script: #!/bin/bash # # DecryptScript.sh # # This script decrypts encrypted data using a symmetric key. # Check for the correct number of arguments if [ "$#" -ne 2 ]; then echo "Usage: $0 <encrypted_file_path> <decrypted_file_path>" exit 1 fi # Get the input arguments encryptedFilePath="$1" decryptedFilePath="$2" # Find the path to the script's directory scriptDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Check if the symmetric key file exists in the same directory symmetricKeyPath="$scriptDir/.sim.key" if [ ! -f "$symmetricKeyPath" ]; then echo "SymmetricKey file was not found in the same directory as the script." exit 1 fi # Decrypt the data swift - <<EOF import Foundation import CryptoKit let symmetricKeyURL = URL(fileURLWithPath: "$symmetricKeyPath") let encryptedDataURL = URL(fileURLWithPath: "$encryptedFilePath") let decryptedDataURL = URL(fileURLWithPath: "$decryptedFilePath") guard let symmetricKeyData = try? Data(contentsOf: symmetricKeyURL) else { fatalError("Failed to read symmetric key data") } guard let encryptedData = try? Data(contentsOf: encryptedDataURL) else { fatalError("Failed to read encrypted data") } do { // Decrypt the data using AES-GCM let decryptionKey = SymmetricKey(data: symmetricKeyData) let sealedBox = try AES.GCM.SealedBox(combined: encryptedData) let decryptedData = try AES.GCM.open(sealedBox, using: decryptionKey) // Write the decrypted data to a file try decryptedData.write(to: decryptedDataURL) print("Decryption successful. Decrypted file saved at \(decryptedDataURL)") } catch { print("Decryption failed: \(error.localizedDescription)") } EOF The code in the project which encrypts the data and retrieves the key: func encryptSymmetric(data: Data, password: String) throws -> (Data, Data) { let key = SymmetricKey(size: .bits256) guard let cipher = try? AES.GCM.seal(data, using: key).combined else { throw SomeCustomError.failedToEncryptData } let keyData = key.withUnsafeBytes { Data($0) } return (cipher, keyData) } The error I'm presented with in the terminal is JIT session error: Symbols not found: [ _$s9CryptoKit3AESO3GCMO4open_5using10Foundation4DataVAE9SealedBoxV_AA12SymmetricKeyVtKFZ, _$s9CryptoKit12SymmetricKeyVMa, _$s9CryptoKit3AESO3GCMO9SealedBoxV8combinedAGx_tKc10Foundation12DataProtocolRzlufC, _$s9CryptoKit12SymmetricKeyV4dataACx_tc10Foundation15ContiguousBytesRzlufC, _$s9CryptoKit3AESO3GCMO9SealedBoxVMa ] Failed to materialize symbols: { (main, { _$s4main16encryptedDataURL10Foundation0D0Vvp, _$s4main15symmetricKeyURL10Foundation0D0Vvp, _$s10Foundation4DataVAcA0B8ProtocolAAWL, _$s4main16decryptedDataURL10Foundation0D0Vvp, _$sSa12_endMutationyyF, _$ss5print_9separator10terminatoryypd_S2StFfA0_, _$ss27_finalizeUninitializedArrayySayxGABnlF, _main, _$s10Foundation4DataV15_RepresentationOWOe, _$sSSWOh, _$ss5print_9separator10terminatoryypd_S2StFfA1_, _$s10Foundation4DataV5write2to7optionsyAA3URLV_So20NSDataWritingOptionsVtKFfA0_, ___swift_allocate_value_buffer, __swift_FORCE_LOAD_$_swiftFoundation_$_main, _$s10Foundation4DataV10contentsOf7optionsAcA3URLVh_So20NSDataReadingOptionsVtKcfcfA0_, __swift_FORCE_LOAD_$_swiftXPC_$_main, _$s10Foundation4DataV15_RepresentationOWOy, ___swift_project_value_buffer, _$s10Foundation4DataVAcA0B8ProtocolAAWl, __swift_FORCE_LOAD_$_swiftIOKit_$_main, _$ss26DefaultStringInterpolationVWOh, __swift_FORCE_LOAD_$_swiftCoreFoundation_$_main, _$s10Foundation3URLVACs23CustomStringConvertibleAAWl, __swift_FORCE_LOAD_$_swiftDarwin_$_main, __swift_FORCE_LOAD_$_swiftObjectiveC_$_main, _$s10Foundation3URLVACs23CustomStringConvertibleAAWL, __swift_FORCE_LOAD_$_swiftDispatch_$_main }) } This leads me to believe that linking might not be working properly. I also found this thread where someone had the same issue but with a different framework. NOTE: If I try to decrypt the data in my project, it works without any issues even on Xcode 15. It only fails if I try to run this script which worked before when I had the previous version of command line tools. I even tried updating to Xcode 15.1 beta and its command line tools, without success. Any feedback is appreciated. Thank you.
2
1
1.2k
Oct ’23
DispatchSerialQueue not conforming to UnownedSerialExecutor in iOS 17.0
I'm playing around with custom actor executors a bit ... as seen in What's new in Swift at WWDC 2023... The following code errors out: @available(iOS 17.0, *) actor TestActor { private let queue: DispatchSerialQueue nonisolated var unownedExecutor: UnownedSerialExecutor { queue.asUnownedSerialExecutor() } ... Value of type 'DispatchSerialQueue' has no member 'asUnownedSerialExecutor' There is the _DispatchSerialExecutorQueue that actually does provide the asUnownedSerialExecutor() function ... This conflicts a bit with what Doug said during the talk... "The synchronization of actors via dispatch queues is made possible because dispatch queue conforms to the new SerialExecutor protocol." https://developer.apple.com/wwdc23/10164?time=2206
1
0
431
Oct ’23
Cannot get eSim implementation although followed everything also getting false for supportsEmbeddedSIM and supportsCellularPlan
Hi Everyone, I have enabled eSIM entitlements to check eSIM, but I am always getting false for supportsCellularPlan and supportsEmbeddedSIM although my device having the esim feature. I followed each step from this stack overflow answer https://stackoverflow.com/a/60162323 Can anyone help me out here? below is the code I used:- private let provisioning = CTCellularPlanProvisioning() let ctpr = CTCellularPlanProvisioningRequest() ctpr.address = "address$" ctpr.matchingID = "string$" let supportsESIM = provisioning.supportsCellularPlan() if #available(iOS 12.0, *) { let ctcp = CTCellularPlanProvisioning() ctcp.addPlan(with: ctpr) { (result) in switch result { case .unknown: print("Sorry unknown error") case .fail: print("Oops! something went wrong") case .success: print("Yay! eSIM installed successfully") @unknown default: print("Oops! something went wrong") } } } print(provisioning.supportsEmbeddedSIM) print(supportsESIM) this is the entitlements SS this is the info.plist SS
2
0
1k
Oct ’23
objc4-818.2 object_cxxDestructFromClass implementation
Below is the implementation of the object_cxxDestructFromClass method. the line below the for loop if (!cls->hasCxxDtor()) return; Some questions: If a subclass inherits a parent class, and one of the middle classes does not have a CxxDtor, but the parent class does, will there be any problems with the release of the instance? static void object_cxxDestructFromClass(id obj, Class cls) { void (*dtor)(id); // Call cls's dtor first, then superclasses's dtors. for ( ; cls; cls = cls->getSuperclass()) { if (!cls->hasCxxDtor()) return; dtor = (void(*)(id)) lookupMethodInClassAndLoadCache(cls, SEL_cxx_destruct); if (dtor != (void(*)(id))_objc_msgForward_impcache) { if (PrintCxxCtors) { _objc_inform("CXX: calling C++ destructors for class %s", cls->nameForLogging()); } (*dtor)(obj); } } }
0
0
392
Oct ’23
Need help on generics where clause
I have the following class: /// Act as a reference container for value types. public class ValueBox<ValueType: ??> { public var value: ValueType public init() { value = ValueType() // Compiler error } public init(_ value: ValueType) { self.value = value } } Is it possible to specify the generic type ValueType can be inited?
1
0
216
Oct ’23
Swift Interop Build Issue - Linker Error with Undefined Symbols when running tests
Hi All, I have a Swift Package I'm building. I need to import an existing C++ Static Library into this package. It seems to build fine, but when I attempt to run the tests I get a weird linker error. I've put a repro repo up at https://github.com/flighttactics/CppIssueRepro Here's the steps I took: I have the C++ library's .a file and the headers. I created a folder in my package for the library, drug the include folder into it, and then added the .a file at the root of the folder. I created an Umbrella header in the include folder, along with a module.modulemap. I then created a shim file (per https://github.com/apple/swift-package-manager/issues/5706) Finally, I modified my package file to build the target, and reference it as a dependency (Note I also had to go into the GeographicLib headers for DST and comment out two functions I'm not using which reference std::function since that's not supported by Swift) I find that including the library module works in the main code base, and I can build successfully. However, when I attempt to run tests against the main code base when it's calling into the C++ library I'm getting the following build error: ld: Undefined symbols: double GeographicLib::Math::AngNormalize<double>(double), referenced from: GeographicLib::GeoCoords::Reset(double, double, int) in CppIssueRepro.o GeographicLib::UTMUPS::Forward(double, double, int&, bool&, double&, double&, double&, double&, int, bool), referenced from: GeographicLib::GeoCoords::Reset(double, double, int) in CppIssueRepro.o GeographicLib::GeoCoords::MGRSRepresentation(int) const, referenced from: CppIssueRepro.CoordinateCalculator.coverttoMGRS(lat: Swift.Double, lon: Swift.Double) -> Swift.String in CppIssueRepro.o clang: error: linker command failed with exit code 1 (use -v to see invocation) Again, if my main code does not call into the C++ library I'm able to run tests and build just fine. Not sure what else I can do - it seems like I'm following everything based on the 5.9 docs but I also feel I'm maybe missing something really simple here.
2
2
794
Oct ’23
Runtime crash on iOS16 when iOS17 framework is mentioned
Hi Everyone, I'm having a strange crash on App launch with iOS16 when I have a reference to an iOS17 only framework in my code. Even if I wrap the code in #available, I still get the crash on launch; and the code isn't even called yet... just the existence of it causes the crash. Pretty strange I thought? The framework is VisionKit, and the code that causes the crash is if #available(iOS 17, *) { // .imageSubject is iOS17 only - but this causes // a crash on launch in iOS16 even with the #available check interaction.preferredInteractionTypes = .imageSubject } The crash is: Referenced from: &lt;91ED5216-D66C-3649-91DA-B31C0B55DDA1&gt; /private/var/containers/Bundle/Application/78FD9C93-5657-4FF5-85E7-A44B60717870/XXXXXX.app/XXXXXX Expected in: &lt;AF01C435-3C37-3C7C-84D9-9B5EA3A59F5C&gt; /System/Library/Frameworks/VisionKit.framework/VisionKit Any thoughts anyone?? I know the .imageSubject is iOS17 only, but the #available should catch it - no? Any why does it crash immediatley on launch, when that code is not even called? Odd!
1
1
693
Oct ’23
Drag gesture is dragging all the images vs the tap and long press gestures just work off clicked image
I would like to be able to use multiple gestures against a number of images. In the code below, when I use the tap (3 times) gesture, it works correctly off the clicked card, same with the long press. However, when I try to drag 1 image, all of them are dragged together. I guess it has something to do with being in the ForEach view? Thanks for looking at this and helping me get out of the rut I have dragged myself into! Here is the code (you can use any images to test, I used playing cards): import SwiftUI struct ContentView: View { enum DragState { case inactive case dragging(translation: CGSize) var translation: CGSize { switch self { case .dragging(let translation): return translation default:return CGSize.zero}}} @GestureState var pressing: Bool = false @GestureState var dragState = DragState.inactive @State var viewDragState = CGSize.zero @State var p1Hand: [String] = ["2_of_hearts", "3_of_hearts", "4_of_hearts", "5_of_hearts"] @State var discardDeck: [String] = [] @State var p1TM1: [String] = [] @State var expand: Bool = false var translationOffset: CGSize { return CGSize(width: viewDragState.width + dragState.translation.width, height: viewDragState.height + dragState.translation.height)} var body: some View { ZStack { ForEach(0..<p1Hand.count, id: \.self) { cardIndex in CardView (card: p1Hand[cardIndex], cardIndex: cardIndex) // 3 taps to move to different array .onTapGesture(count: 3, perform: { discardDeck.append(p1Hand[cardIndex]) print("discard: \(discardDeck)") }) // long press put in another array .gesture(LongPressGesture(minimumDuration: 1) .updating($pressing) {value,state,transaction in state = value transaction.animation = Animation.easeInOut(duration: 0.5) } .onEnded { value in expand = true p1TM1.append(p1Hand[cardIndex]) print("p1TM1: \(p1TM1)") }) // drag card to group .gesture(DragGesture(minimumDistance: 5) .updating($dragState) { value, state, translation in state = .dragging(translation: value.translation) }.onEnded { value in self.viewDragState.height += value.translation.height self.viewDragState.width += value.translation.width print("card(s) dragged") }) .offset(translationOffset) } } } } struct CardView: View { var card: String var cardIndex: Int var body: some View { Image(card) .resizable() .frame(width: 40, height: 60) .position(x: 40 + CGFloat(cardIndex * 25), y:75) } } #Preview { ContentView() }
0
0
280
Oct ’23
Weird error with HTTPS connection
I have a weird problem with HTTPS connection. Task <A19A5441-F5CD-4F8C-8C88-73FC679D8AE0>.<1> finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." I am trying to bypass server certificate of my website because it's self-signed. The following code works in a test app, but not in another app. They have exactly have the same entitlements: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>com.apple.security.app-sandbox</key> <true/> <key>com.apple.security.files.user-selected.read-write</key> <true/> <key>com.apple.security.network.client</key> <true/> </dict> </plist> func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { let protectionSpace = challenge.protectionSpace guard protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, protectionSpace.host.contains("mywebsite.net") else { completionHandler(.performDefaultHandling, nil) return } guard let serverTrust = protectionSpace.serverTrust else { completionHandler(.performDefaultHandling, nil) return } let credential = URLCredential(trust: serverTrust) completionHandler(.useCredential, credential) } @IBAction func testMenuItem_select(_ sender: Any) { print("\(sender)") Preferences.instance.openTipShowed = false testURLSession() func testURLSession() { let session = URLSession(configuration: URLSessionConfiguration.ephemeral, delegate: self, delegateQueue: nil) let url2 = "https://www.mywebsite.net/spiders.txt" let url3 = "https://www.apple.com/" let url = URL(string: url2)! var request = URLRequest(url: url) let task = session.dataTask(with: request) { data, response, error in if let error { print(error) } if let data { let text = String(data: data, encoding: .utf8) print("HTTP response object:", response ?? "") print("HTTP resonse text:", text ?? "<empty response>") } } task.resume() } }
1
0
423
Oct ’23