I'm primarily an AppleScript writer and only a novice programmer, using ChatGPT to help me with the legwork. It has helped me to write a functioning app that builds a menu structure based on the scripts I have in the Scripts directory used in the script menu and then runs the applescripts. When I distribute the app to my desktop and run it, the scripts that access other apps, like InDesign will cause it to launch, but not actually do anything. I included the ids for each app in the entitlements dictionary and have given the app full disk access in system settings, but it's not functioning as I'd expect.
I know there are apps like Alfred that allow you to run scripts from a keystroke, but I'm building this for others I work with so they can also access info about each script, what it does, and how to use it from the menu, as well as key commands to run them.
Not sure what else to say, but if this sounds like a simple fix to anyone, please let me know.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I've been searching all over the web trying to find the proper way to get all records created by a specific user in CloudKit.
I am able to get the correct id using:
guard let userRecordID = try? await container.userRecordID() else { return }
I can see that the id returned is associated with records in my CloudKit dashboard. So I would expect that the following would get those records:
let predicate = NSPredicate(format: "%K == %@", #keyPath(CKRecord.creatorUserRecordID), userRecordID)
let query = CKQuery(recordType: "CKUser", predicate: predicate)
But instead when I use that query it returns nothing. It is successful but with nothing returned...
Any ideas why this would be happening?
P.S. I have also tried constructing the predicate using the reference, but I get the same result - success with no results.
P.S.2 Also worth mentioning that I am trying to get the results from the public database and I have set my CKContainer to the correct container id.
A program I wrote in Swift that uploads and downloads to a private database in iCloud is failing for downloads since the the 15.2 update.
It still works for uploads. I.e., I can download uploads made from the program under 15.2 on another computer running the same program under 15.1
The Fetch operation does not return an error, but the returnRecord is empty!
I do get the error below after the fact of the failure, don't know if it's related.
"ViewBridge to RemoteViewService Terminated: Error Domain=com.apple.ViewBridge Code=18 "(null)" UserInfo={com.apple.ViewBridge.error.hint=this process disconnected remote view controller -- benign unless unexpected, com.apple.ViewBridge.error.description=NSViewBridgeErrorCanceled}"
To be clear, I assume I do have access to the database since it works for upload under 15.2, as well as upload and download under 15.1, and from a very similar program on my iPhone (which I haven't updated yet!)
Questions? Comments?
Thanks!
Topic:
Programming Languages
SubTopic:
Swift
I noticed that when I enter the fully immersive view and then click the X button below the window, the immersive space remains active, and the only way to dismiss it is to click the digital crown. On other apps (Disney+ for example), closing out of the main window while in immersive mode also closes out the immersive space. I tried applying an onDisappear modifier to the the Modules view with a dismissImmersiveSpace, but that doesn't appear to do anything.
Any help would be appreciated.
I have an xcode project which has both cpp and swift code. In one of my usecase I am passing primitive type variables from swift to cpp by reference( primitives types list here as per the new cpp-swift interop documentation)
swift code:
// primitive check code:Bool
var x : Bool = true
// When we are passing a variable as a Reference, we need to use explicitly use'&'
student.PassBoolAsReferenceType (&x) // interop call to cpp code
print (x)
Cpp code:
void
Student::PassBoolAsReferenceType(bool &pValue) noexcept
{
std::cout << pValue << std::endl;
pValue = false;
}
The above code fails during compilation with no clear error message "Command SwiftCompile failed with a nonzero exit code"
However, all the other primitive types that I tested worked for the above code like Int, Float, Double etc. Only the Bool interop fails. Can someone explain why is it not possible for bool? I m using the new interop introduced in swift 5.9.
Hello Everyone,
I have a use case where I wanted to interpret the "Data" object received as a part of my NWConnection's recv call. I have my interpretation logic in cpp so in swift I extract the pointer to the raw bytes from Data and pass it to cpp as a UnsafeMutableRawPointer.
In cpp it is received as a void * where I typecast it to char * to read data byte by byte before framing a response.
I am able to get the pointer of the bytes by using
// Swift Code
// pContent is the received Data
if let content = pContent, !content.isEmpty {
bytes = content.withUnsafeBytes { rawBufferPointer in
guard let buffer = rawBufferPointer.baseAddress else {
// return with null data.
}
// invoke cpp method to interpret data and trigger response.
}
// Cpp Code
void InterpretResponse (void * pDataPointer, int pDataLength) {
char * data = (char *) pDataPointer;
for (int iterator = 0; iterator < pDataLength; ++iterator )
{
std::cout << data<< std::endl;
data++;
}
}
When I pass this buffer to cpp, I am unable to interpret it properly.
Can someone help me out here?
Thanks :)
Harshal
Hey team I'm facing an issue where startDate is 1 January 2025 and endDate is 31 March 2025 between this 2 dates is 90 days, but on my code is being taken as 89 days
I've seen the math of the code excludes the first partial day (from midnight to 06:00) on 2025-01-01, which results in 89 full days instead of 90 days.
startDate: 2025-01-01 06:00:00 +0000
endDate: 2025-03-31 06:00:00 +0000
this is my function
func daysBetweenDates() -> Int? {
guard let selectedStartDate = selectedStartDate?.date else { return nil }
guard let selectedEndDate = selectedEndDate?.date else { return 0 }
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.day], from: selectedStartDate, to: selectedEndDate)
return dateComponents.day
}
what I've tried is reset the hours to 0 so it can take the full day and return 90 days
like this
func daysBetweenDates() -> Int? {
guard let selectedStartDate = selectedStartDate?.date else { return nil }
guard let selectedEndDate = selectedEndDate?.date else { return 0 }
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0) ?? .current
let cleanMidNightStartDate = calendar.startOfDay(for: selectedStartDate)
let cleanMidNightEndDate = calendar.startOfDay(for: selectedEndDate.addingTimeInterval(24 * 60 * 60))
let dateComponents = calendar.dateComponents([.day], from: cleanMidNightStartDate, to: cleanMidNightEndDate)
let daysCount = dateComponents.day ?? 0
return daysCount
}
this worked for that date specifically but when I tried to change the date for example
startDate: 18 December 2024.
endDate: 18 March 2025.
between those dates we have 90 days but this function now reads 91.
what I'm looking is a cleaver solution for this problem so I can have the best posible quality code, thanks in advance!
Topic:
Programming Languages
SubTopic:
Swift
I have been trying to integrate a UIKit view into SwiftUI, specifically a WKWebView. However, I keep encountering a does not conform to protocol error.
Here's my code:
import SwiftUI
import WebKit
struct SimpleWebView: View {
var body: some View {
WebViewContainerRepresentable()
.edgesIgnoringSafeArea(.all)
}
}
struct WebViewContainerRepresentable: UIViewRepresentable {
typealias UIViewType = WKWebView
func makeUIView(context: Context) -> WKWebView {
let webView = WKWebView()
if let url = Bundle.main.url(forResource: "index", withExtension: "html") {
webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
}
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {
// Updates not required for this use case
}
}
I tried this with other views as well, and it turns out this is not WKWebView-specific.
The minimum deployment version is iOS 15.
Any help would be much appreciated. Let me know if I need to add any more information.
I'm using xcode 16.1 withSwift. I want to know how to call a function passing in an array. Also I need to know how to declare the function receiving the array. I currently have:
func myfunc(costa: [Double]) {
}
I call it like this:
myfunc(costa:[ ])
It's an array of Doubles. I don't get any errors but the array is always empty. Please help. Thank you.
Topic:
Programming Languages
SubTopic:
Swift
Decrypting Data to String Conversion failure
Development environment: Xcode 15.4, macOS 14.7
Run-time configuration: iOS 15.8.1 & 16.0.1
DESCRIPTION OF PROBLEM
We were using objective C implementation of CCCrypt(see below) in our app earlier which we migrated to swift implementation recently. We convert the byte array that CCCrypt returns into Data, and data to string to read the decrypted value. It works perfectly fine in Objective C, whereas with new swift implementation this conversion is failing, it looks like CCCrypt is returning byte array with few non UTF8 characters and that conversion is failing in swift since Objective C is more tolerant with this conversion and converts the byte array to Data and then to string even though there are few imperfect UTF characters in the array.
Objective C
CCCryptorStatus CCCrypt(
CCOperation op, /* kCCEncrypt, etc. /
CCAlgorithm alg, / kCCAlgorithmAES128, etc. /
CCOptions options, / kCCOptionPKCS7Padding, etc. */
const void *key,
size_t keyLength,
const void iv, / optional initialization vector */
const void dataIn, / optional per op and alg */
size_t dataInLength,
void dataOut, / data RETURNED here */
size_t dataOutAvailable,
size_t *dataOutMoved)
API_AVAILABLE(macos(10.4), ios(2.0));
Swift Code
CCCrypt(_ op: CCOperation,
_ alg: CCAlgorithm,
_ options: CCOptions,
_ key: UnsafeRawPointer!,
_ keyLength: Int, _ iv: UnsafeRawPointer!,
_ dataIn: UnsafeRawPointer!,
_ dataInLength: Int,
_ dataOut: UnsafeMutableRawPointer!,
_ dataOutAvailable: Int,
_ dataOutMoved: UnsafeMutablePointer!) -> CCCryptorStatus
Data to String Conversion
String(data: decryptedData, encoding: .utf8)
STEPS TO REPRODUCE
Able to reproduce on below devices
iPhone - 7
OS Version 15.8.1
iPhone 14- Pro
OS Version 16.0.2
iPhone 15
iOS 18.0.1
**Decryption method return "Data" and converting into string using ".utf8" but String conversion is failing on above devices and some other devices as well. Decryption failure not occurring always.
**
Below code used for String conversion
String(data: decryptedData, encoding: .utf8)
My application crash on iOS 16 randomly, stack trace like this:
libswiftCore.dylib __swift_release_dealloc + 32
libswiftNetwork.dylib outlined consume of (@escaping @callee_guaranteed (@in_guaranteed Network.NWConnection.State) -> ())? + 52
libswiftNetwork.dylib outlined consume of (@escaping @callee_guaranteed (@in_guaranteed Network.NWConnection.State) -> ())? + 52
libswiftCore.dylib __swift_release_dealloc + 56
libsystem_blocks.dylib __call_dispose_helpers_excp + 48
libsystem_blocks.dylib __Block_release + 252
libsystem_blocks.dylib bool HelperBase::disposeCapture<(HelperBase::BlockCaptureKind)4>(unsigned int, unsigned char*) + 68
libsystem_blocks.dylib HelperBase::destroyBlock(Block_layout*, bool, unsigned char*) + 180
libsystem_blocks.dylib __call_dispose_helpers_excp + 72
libsystem_blocks.dylib __Block_release + 252
libdispatch.dylib ___destroy_helper_block_8_32c35typeinfo name for dispatch_block_private_data_s + 96
libsystem_blocks.dylib __call_dispose_helpers_excp + 48
libsystem_blocks.dylib __Block_release + 252
libdispatch.dylib __dispatch_client_callout + 20
libdispatch.dylib __dispatch_root_queue_drain + 684
libdispatch.dylib __dispatch_worker_thread2 + 164
libsystem_pthread.dylib __pthread_wqthread + 228
From buly(a tool to report crash) we notice that this crash only happens on iOS 16
Topic:
Programming Languages
SubTopic:
Swift
I want to know how to format doubles. In the program I have 4.3333 I just want to print 4 to the screen. I just want to print whole numbers. I'm using Swiftui with xcode. Please help. Thank you.
Topic:
Programming Languages
SubTopic:
Swift
Hi,
I'm struggling to understand using Swift-C++ in the same project. I have an existing code-base that makes heavy use of Swift-Objective-C interoperability.
We make use of swift classes in our project. When I enable swift-objective c interoperability I am running into numerous build errors in the generated bridging header.
I'm trying to understand why these errors exist and what to do to get around them.
I have a project that I've set up with some test code, and I'm running into an error here:
public class Foo {
let name: String
public init(name: String) {
self.name = name
}
}
public class Bar {
let name: String
public init(name : String) {
self.name = name;
}
public func getFoo() -> Foo {
return Foo(name: self.name);
}
}
In the header file:
Unknown type name 'Foo'
SWIFT_INLINE_THUNK Foo getFoo() SWIFT_SYMBOL("s:13ForestBuilder3BarC6getFooAA0E0CyF");
This error goes away if I use structs, but for the purposes of porting my codebase, I'd prefer to use classes. Do classes not play nice here? Or am I misunderstanding something.
Thanks.
I am porting an old app from ObjC. The app uses many defined constants such as:
#define COM_OFFSET 12.5
and many variables that are read and/or written throughout the App, such as:
PCDate* Dates[367];
@class PCMainView;
PCMainView* MainView;
in one file called "PCCommon.h"
How do I duplicate this function in Swift? I have looked around and have found no help.
Thanks in advance.
We would like to show a user-friendly message but can not.
Description:
When attempting to create a duplicate passkey using the ASAuthrorizationController in iOS, the Face ID authentication times out SDK does not return a timeout specific error. Instead, it directly returns an error stating that duplicate passkey cannot be created.
SDK to first handle the FaceID timeout case and provide a distinct timeout error so we can gracefully manage this scenario before the duplicate passkey validation occurs.
Steps to Reproduce:
Implement passkey creation flow using ASAuthorizationController.
Attempt to register a duplicate passkey (e.g., using the same user ID and challenge).
Let FaceID prompt timeout (do not interact with the authentication prompt).
Topic:
Programming Languages
SubTopic:
Swift
I recently submitted my app, Hogs, to the App Store, but it was rejected due to references to non-public symbols:
_lzma_code
_lzma_end
I am using the LZMA compression library in my app, and these functions are part of that implementation. Here's a breakdown of my usage:
Library Used: liblzma (custom wrapper around LZMA functions)
Error Message: "The app references non-public symbols in Payload/Hogs.app/Hogs: _lzma_code, _lzma_end."
Steps I’ve Taken:
I’ve wrapped the LZMA functions in my own functions (my_lzma_code, my_lzma_end) to prevent direct references.
I have checked the build settings and included -lzma in the linker flags.
I’ve tried using a custom framework to encapsulate LZMA, but the issue persists.
I would greatly appreciate any help or suggestions on how to resolve this issue and get my app approved. Is there any workaround or adjustment I can make to avoid using these non-public symbols?
Thank you in advance for your assistance.
Hello,
I have integrated LZMA2 compression into my iOS app, Hogs, and successfully implemented compression. However, when attempting to upload the app for TestFlight, I encountered an error:
"The app references non-public symbols in Payload/Hogs.app/Hogs: _lzma_code, _lzma_end."
These functions are part of the LZMA compression library (specifically LZMA2). Here's a detailed description of the issue:
What I Have Done:
LZMA2 Integration: I integrated LZMA2 compression into the app and created a wrapper around the LZMA functions (_lzma_code, _lzma_end) to prevent direct references.
App Build Configuration:
I ensured the LZMA2 library is linked correctly with the -lzma flag in the linker settings.
I wrapped the LZMA functions in custom functions (my_lzma_code, my_lzma_end) in an attempt to avoid using the non-public symbols directly.
Error Message:
During the app submission process, I received the following error:
"The app references non-public symbols in Payload/Hogs.app/Hogs: _lzma_code, _lzma_end."
Steps Taken to Resolve:
Checked if any LZMA functions were exposed incorrectly.
Ensured that all non-public symbols were properly encapsulated in a wrapper.
Verified linker settings to ensure the proper inclusion of the LZMA2 library.
Request:
Could anyone provide suggestions or best practices to resolve this issue and avoid references to non-public symbols? Should I use a different method for linking LZMA2 or encapsulating these symbols?
Thank You:
I appreciate your help in resolving this issue so I can move forward with submitting the app for TestFlight.
Topic:
Programming Languages
SubTopic:
Swift
Tags:
Swift Packages
Apple Archive
Compression
TestFlight
I was a long time C# programmer, and recently started learning Rust. Now that I recently purchased my first Mac, I ran into several issues trying to run binaries on the Mac, due to various restrictions. On another forum post here, it was mentioned that I should take a look at Swift, as a development tool.
This comment brings up an entirely new topic for me, as I discovered that the Swift project file structure seems daunting. But first let's backtrack to when I used C#.
C#
The first graphic show the default file structure that I used to start a new C# project. I would copy this entire folder structure to the clipboard and paste it where my new project folder was located, and start coding.
Using this same principle, I wrote my own music player, and again the file structure for the entire project was as below. For those that may not know, the "bin" folder contains both debug and release folders and appropriate contents.
Swift
I created a Windows UI called "Test" using Swift, and then started poking around the file system, trying to determine the file structure that was created. Unbeknownst to me at the time, part of the project files ended up on the Desktop in a folder called Test. I did not expect Swift to place the files there.
When I click on the Test folder and look inside, I see a file with a "xcodeproj" extension, which makes sense to me, as this is similar to C#. What I don't see however, is any file labeled Test.App. I also don't see either debug or release folders for this project.
Obviously there are additional files for this project that are "somewhere", just not in a location I am aware of.
Topic:
Programming Languages
SubTopic:
Swift
I have enabled runtime concurrency warnings to check for future problems concerning concurrency: Build Setting / Other Swift Flags:
-Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks
When trying to call the async form of PHPhotoLibrary.shared().performChanges{} I get the following runtime warning: warning: data race detected: @MainActor function at ... was not called on the main thread in the line containing performChanges.
My sample code inside a default Xcode multi platform app template is as follows:
import SwiftUI
import Photos
@MainActor
class FotoChanger{
func addFotos() async throws{
await PHPhotoLibrary.requestAuthorization(for: .addOnly)
try! await PHPhotoLibrary.shared().performChanges{
let data = NSDataAsset(name: "Swift")!.data
let creationRequest = PHAssetCreationRequest.forAsset()
creationRequest.addResource(with: .photo, data: data, options: PHAssetResourceCreationOptions())
}
}
}
struct ContentView: View {
var body: some View {
ProgressView()
.task{
try! await FotoChanger().addFotos()
}
}
}
You would have to have a Swift data asset inside the asset catalog to run the above code, but the error can even be recreated if the data is invalid.
But what am I doing wrong? I have not found a way to run perform changes, the block or whatever causes the error on the main thread.
PS: This is only test code to show the problem, don't mind the forced unwraps.
Hi, I want to create a dashboard in a app using swift playgrounds with esp 32 and a led. The dashboard should have a toggle switch to toggle the switch state like on/off for the led once i get the basics i want to create a full dashboards with things like gauges, sliders, button and many more. Can someone please help/guide me.
Thanks.
Topic:
Programming Languages
SubTopic:
Swift