I'm trying to create swift macros for initializer. I can't get the members of the inherited class.
Dive into the world of programming languages used for app development.
Post
Replies
Boosts
Views
Activity
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?
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.
I'm using the latest Playground app (version 4.3.1) and Xcode 15. I'd like to practice code that supports iOS 12 and above. Is there a way to set the deployment target in either the standalone Playground app or within Xcode playgrounds?
Hello, I am using swift to develop an app.
I created a new swift file called PDFkithelper it is in the same folder but the viewcontroller is not recognizing it.
can I get help?
This is For view controller.
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
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.
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?
I am trying to play multiple HLS streams with AVPlayer. Starting with 4 cameras it is working fine but whenever I change cameras, it stuck with
AVPlayer.TimeControlStatus.waitingToPlayAtSpecifiedRate. it is working fine with iOS 15 but having issues with iOS 16 and 17. I have checked it with different network speeds. So bandwidth is fine.
I want to access to a small number of Markdown text files. It looks like the asset catalog feature "Folder with Namespace" might do well, as I could store these small files in a folder that the asset catalog contains. How would I go about getting the string contents of a particular file if I know its name?
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.
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
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
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);
}
}
}
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?
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.
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: <91ED5216-D66C-3649-91DA-B31C0B55DDA1> /private/var/containers/Bundle/Application/78FD9C93-5657-4FF5-85E7-A44B60717870/XXXXXX.app/XXXXXX
Expected in: <AF01C435-3C37-3C7C-84D9-9B5EA3A59F5C> /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!
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()
}
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()
}
}