Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

Issue starting Live Activities with ActivityKit push notifications
Hi all, I'm trying to implement starting Live Activities with push notifications according to this article: https://developer.apple.com/documentation/activitykit/starting-and-updating-live-activities-with-activitykit-push-notifications I'm using Xcode 15.1 beta 3, I have run my tests on a physical device with iOS 17.2 as well as the simulator with iOS 17.2 My problem is I can't seem to be able to get the pushToStartToken needed to start the live activities. I have subscribed to the pushToStartTokenUpdates but I never get any updates. Here is the code I used: Task { do { for try await data in Activity<DailyGoalActivityAttributes>.pushToStartTokenUpdates { let token = data.map {String(format: "%02x", $0)}.joined() print("Activity token: \(token)") } } catch { print(error) } } Any help would be greatly appreciated. Thanks, HS
12
5
5.6k
Nov ’23
Unable to verify App
While using the application, it suddenly quits. When we attempt to reopen it, an error pop-up appears stating, 'Unable to verify app. Internet connection is required to verify trust.' We tried accessing the VPN and regularity options in settings, and clicked on 'Trust,' but it was ineffective. The only solution that works is resetting the iPad. However, after one or two days, the same issue arises again. This problem seems to occur exclusively on certain iPads. What might be causing this recurring problem?"
6
2
2.7k
Nov ’23
SwiftData @Model Codable conformance for array of structs
I have a struct that is identifiable, and has two String variables and a UUID. I am using @Model decorator/macro for a class I want to persist, which has a few String variables (with values assigned to them), and some arrays of my struct, which are assigned values with the init() initialiser. This class also has two functions, both of which return an integer. I am getting many errors for the String variables and initialisation of the arrays of structs: Referencing instance method 'setValue(forKey:to:)' on 'Array' requires that 'Record' conform to 'PersistentModel' No exact matches in call to instance method 'setValue' No exact matches in call to instance method 'getValue' I tried converting the struct to class, but that did not help. I also tried writing my own encoder and decoder functions, but that did not help either. // Created by Devansh Trivedi on 24/11/23. // import SwiftUI // For UUID() to make Record struct Identifiable import SwiftData struct Record : Identifiable { var date: String var value: String var id = UUID() } @Model class Card { //https://www.donnywals.com/making-your-swiftdata-models-codable/ // enum CodingKeys: CodingKey { // case unit, date, name // } // required init(from decoder: Decoder) throws { // let container = try decoder.container(keyedBy: CodingKeys.self) // self.unit = try container.decode(String.self, forKey: .unit) // self.date = try container.decode(String.self, forKey: .date) // self.name = try container.decode(String.self, forKey: .name) // } // func encode(to encoder: Encoder) throws { // var container = encoder.container(keyedBy: CodingKeys.self) // try container.encode(unit, forKey: .unit) // try container.encode(date, forKey: .date) // try container.encode(date, forKey: .name) // } var unit:String="Liters" var date:String="Nov 23" var name:String="Milk" var column_1:[Record] var column_2:[Record] var column_3:[Record] init() { self.column_1 = [ Record(date: "1", value: ""), Record(date: "2", value: ""), Record(date: "3", value: ""), Record(date: "4", value: ""), Record(date: "5", value: ""), Record(date: "6", value: ""), Record(date: "7", value: ""), Record(date: "8", value: ""), Record(date: "9", value: ""), Record(date: "10", value: "") ] self.column_2 = [ Record(date: "11", value: ""), Record(date: "12", value: ""), Record(date: "13", value: ""), Record(date: "14", value: ""), Record(date: "15", value: ""), Record(date: "16", value: ""), Record(date: "17", value: ""), Record(date: "18", value: ""), Record(date: "19", value: ""), Record(date: "20", value: "") ] self.column_3 = [ Record(date: "21", value: ""), Record(date: "22", value: ""), Record(date: "23", value: ""), Record(date: "24", value: ""), Record(date: "25", value: ""), Record(date: "26", value: ""), Record(date: "27", value: ""), Record(date: "28", value: ""), Record(date: "29", value: ""), Record(date: "30", value: ""), Record(date: "31", value: "") ] } func total() -> Int { // https://hoyelam.com/summing-up-numeric-properties-of-objects-in-an-array-in-swift/ // https://dev.to/hoyelam/summing-up-numeric-properties-of-objects-in-an-array-in-swift-4og return column_1.lazy .filter( { !$0.value.isEmpty } ) .map( { Int($0.value)! } ) .reduce(0, +) + column_2.lazy .filter( { !$0.value.isEmpty } ) .map( {Int($0.value)! }) .reduce(0, +) + column_3.lazy .filter({!$0.value.isEmpty}) .map( {Int($0.value)! }) .reduce(0, +) } func bill() -> Int { return self.total()*65 } }
2
2
1.6k
Nov ’23
Is there an opposite of @available?
I got tried of the compiler telling me that .onChange(of:) was deprecated, so I thought, find, I'll simply stub it out for the older versions. Only... I can't seem to do that? I can use @available(macOS 14, *) to build for that and later, but is there any way to do the opposite? (I'd hoped there was a #if available support, but there isn't.)
4
0
660
Nov ’23
Implementing SECP256R1 Signature Matching with Rust's FastCrypto in Swift
Hello fellow developers, I'm currently working on an SDK involving the SECP256R1 standard and facing an interesting issue. My goal is to ensure the Swift implementation of SECP256R1 signatures matches that of Rust's FastCrypto implementation. The Issue: When running tests to compare signatures generated by Swift and Rust implementations, the signatures do not match. Despite this mismatch, verification tests still succeed. I've tried using both the P256 class from CryptoKit and SecKey from the Security SDK. The Swift code is being written in Xcode 15 Beta 8, Swift 5.9. Code Snippet: struct SECP256R1PrivateKey { /// Commented is P256, uncommented is SecKey // public init(key: Data) throws { // if let privateKey = try? P256.Signing.PrivateKey(rawRepresentation: key) { // self.key = privateKey // } else { // throw AccountError.invalidData // } // } public init(key: Data) throws { if let privateKeyP256 = try? P256.Signing.PrivateKey(rawRepresentation: key) { let attributes: [String: Any] = [ kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, kSecAttrKeyType as String: kSecAttrKeyTypeECDSA, kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave, kSecAttrKeySizeInBits as String: 256 ] var error: Unmanaged<CFError>? guard let privateKey = SecKeyCreateWithData(privateKeyP256.rawRepresentation as CFData, attributes as CFDictionary, &error) else { throw error?.takeRetainedValue() as Error? ?? NSError(domain: NSOSStatusErrorDomain, code: Int(errSecParam), userInfo: nil) } self.key = privateKey } else { throw AccountError.invalidData } } // public func sign(data: Data) throws -> Signature { // let signature = try self.key.signature(for: data) // return Signature( // signature: signature.rawRepresentation, // publickey: try self.publicKey().key.compressedRepresentation, // signatureScheme: .SECP256R1 // ) // } public func sign(data: Data) throws -> Signature { let dataHash = Data(data.sha256) var error: Unmanaged<CFError>? guard let signature = SecKeyCreateSignature(self.key, .ecdsaSignatureMessageX962SHA256, dataHash as NSData, &error) as Data? else { throw error!.takeRetainedValue() as Error } guard let publicKey = SecKeyCopyExternalRepresentation(try self.publicKey().key, &error) as Data? else { throw AccountError.invalidData } return Signature( signature: signature, publickey: publicKey, signatureScheme: .SECP256R1 ) } } func testThatTheRustImplementationForSignaturesIsTheSame() throws { let account = try Account(privateKey: Data(self.validSecp256r1SecretKey), accountType: .secp256r1) guard let signData = "Hello, world!".data(using: .utf8) else { XCTFail("Unable to encode message"); return; } let signature = try account.sign(signData) XCTAssertEqual( try signature.hex(), "26d84720652d8bc4ddd1986434a10b3b7b69f0e35a17c6a5987e6d1cba69652f4384a342487642df5e44592d304bea0ceb0fae2e347fa3cec5ce1a8144cfbbb2" ) } The Core Question: How do I implement the R1 signature in Swift so that it matches the signature generated by Rust's FastCrypto? Any insights, suggestions, or sample code snippets that could guide me in the right direction would be immensely appreciated! Thank you in advance!
4
1
1.3k
Nov ’23
Error setting up camera using DiscoverySession
Trying to access camera hardware using let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: AVCaptureDevice.Position.front) guard let captureDevice = deviceDiscoverySession.devices.first else { print("Failed to get the camera device") } In many devices I get the Failed to get camera device error. Devices like iPhone XS iPhone X iPhone 7 iPhone 11 iPhone 11 Pro Max iPhone 8 iPhone14,7 iPhone 12 iPhone XR iPhone SE (2nd generation) iPhone 13 iPhone 13 Pro iPhone 6s iPhone 6s Plus Is there a reason why this might happen if the hardware is functioning properly. Please help as a lot of users are facing this issue.
2
0
499
Nov ’23
Digital signature to PDF file on Swift/Objective-C
Hi there, Currently, I'm assigned to do the task that allow user can sign their digital signature on iPhone. I've researched for a week and so far, I'm lost on my way. I want to ask your all experience in working the similar task. My demand is: Allow users upload PDF document Then, allow users sign their digital signature Please give me a logic, step and how it works programmatically to research, in order to do this task. Thank you all <3
1
0
460
Nov ’23
CIImage.clampedToExtent() doesn't fill some edges
Hi, I'm trying to find an explanation to strange behaviour of .clampedToExtent() method: I'm doing pretty strait forward thing, clamp the image and then crop it with some insets, so as a result I expert same image as original with padding on every side with repeating last pixel of each edge (to apply CIPixellate filter then), here is the code: originalImage .clampedToExtent() .cropped(to: originalImage.extent.insetBy(dx: -50, dy: -50)) The result is strange: In the result image image has padding as specified, but only there sides have content there (left, right, bottom) and top side has transparent padding. Sometimes right side has transparency instead of content. So the question is why this happens and how to get all sides filled with last pixel data? I tested on two different devices with iOS 16 and 17.
2
0
970
Nov ’23
Securing paywalled features macOS app
Hello, I'm currently developing a SwiftUI app for macOS that includes both free and premium features. One of the features is the maximum amount of items that can be stored in the app: the free version allows users to store up to 10 items, whereas premium users can store up to 1000. The issue I'm facing is with securing the premium feature. I'm using UserDefaults to store the value of the feature, with a key named maxStorageSize. The user can configure this using a dropdown (there are also other options between 10 and 1000). For non-premium users, this dropdown is disabled and set to a default of 10. For premium users, the dropdown is enabled and thus the user can change the setting to a higher value. However, I've realised that this limitation can be bypassed by using the defaults CLI tool to change the value of maxStorageSize underneath the application's knowledge, effectively circumventing the premium requirement. My current workaround is: check the user defaults on launch and if the user is non-premium and any of the premium features have been changed: reset them. continuously monitor for updates on the defaults and if the user is non-premium and a premium feature value has been changed: reset it. This seems to work but feels a little hacky. I'm wondering what mechanisms you've come up with to solve this.
2
0
455
Dec ’23
How read image file metadata?
I want to read metadata of image files such as copyright, author etc. I did a web search and the closest thing is CGImageSourceCopyPropertiesAtIndex: - (void)tableViewSelectionDidChange:(NSNotification *)notif { NSDictionary* metadata = [[NSDictionary alloc] init]; //get selected item NSString* rowData = [fileList objectAtIndex:[tblFileList selectedRow]]; //set path to file selected NSString* filePath = [NSString stringWithFormat:@"%@/%@", objPath, rowData]; //declare a file manager NSFileManager* fileManager = [[NSFileManager alloc] init]; //check to see if the file exists if ([fileManager fileExistsAtPath:filePath] == YES) { //escape all the garbage in the string NSString *percentEscapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)filePath, NULL, NULL, kCFStringEncodingUTF8); //convert path to NSURL NSURL* filePathURL = [[NSURL alloc] initFileURLWithPath:percentEscapedString]; NSError* error; NSLog(@"%@", [filePathURL checkResourceIsReachableAndReturnError:error]); //declare a cg source reference CGImageSourceRef sourceRef; //set the cg source references to the image by passign its url path sourceRef = CGImageSourceCreateWithURL((CFURLRef)filePathURL, NULL); //set a dictionary with the image metadata from the source reference metadata = (NSDictionary *)CGImageSourceCopyPropertiesAtIndex(sourceRef,0,NULL); NSLog(@"%@", metadata); [filePathURL release]; } else { [self showAlert:@"I cannot find this file."]; } [fileManager release]; } Is there any better or easy approach than this?
1
0
790
Dec ’23
Clarification on MFi Certification Capabilities for Enhanced Bluetooth Functionality
Hello Apple Developer Community, I represent a team working on an iOS application that interacts with a Bluetooth Low Energy (BLE) module in vehicles. We're exploring advanced functionalities and have a couple of queries: Automatic PIN Handling: Is there a method for our app to programmatically input a PIN for Bluetooth pairing, bypassing the usual popup prompt? We aim to streamline the user experience by eliminating manual PIN entry. Programmatic Bond Management: Can our app directly "forget" a paired Bluetooth device without requiring the user to manually do so in the iOS settings? This feature would significantly enhance our app's usability. MFi Certification Benefits: Would obtaining MFi certification enable any of the above functionalities, or provide us with additional APIs or capabilities to manage Bluetooth connections more effectively? We appreciate any guidance or insights you can provide on these matters. Understanding these capabilities is crucial for the development of our application. Thank you in advance for your assistance. Best regards,
0
0
356
Dec ’23
Confused about LLDB's "p" and "expr" commands
As I was watching WWDC19 Session: "LLDB: beyond "po" " I got confused about "p" command. In the session there was a following example to show how "p" command works: // Struct for demonstration purposes struct Trip { var name: String var destinations: [String] let cruise = Trip ( name: "Mediterranean Cruise" destinations: ["Sorrento", "Capri", "Taormina"]) Using "p" to get info about cruise instance: (lldb) p cruise (Travel.Trip) $R0 = { name = "Mediterranean Cruise" destinations = 3 values { [0] = "Sorrento" [1] = "Capri" [2] = "Taormina" } } I was following along and wrote the same code. But the output from LLDB turned out to be different: (lldb) p cruise (LLDB_Apple_Session_FollowAlong.Trip) { name = "Mediterranean Cruise" destinations = 3 values { [0] = "Sorrento" [1] = "Capri" [2] = "Taormina" } } As you can see LLDB didn't create a global variable R0 which I could later use in my debugging session and that seemed strange to me. Then the presenter said the following: "p" is just an alias for the "expression" command. So, I tried to use the "expr" command to see if they're actually the same and they turned out to be different commands. The output I got from "expr" was the one I expected from "p": (lldb) expr cruise (LLDB_Apple_Session_FollowAlong.Trip) $R0 = { name = "Mediterranean Cruise" destinations = 3 values { [0] = "Sorrento" [1] = "Capri" [2] = "Taormina" } } Finally, my question is: Am I wrong somewhere or did something change in LLDB regarding "p" and "expr" commands and if so, where could I get more information about the changes?
2
0
956
Dec ’23
Command CodeSign failed with a nonzero exit code
can someone please help me, I am new to using Xcode and SwiftUI, I recently updated to Sonoma and now am having issues building and running projects. i am creating this for a class assignment due in a few days any help is appreciated. currently I am having this error upon simply creating a new file: " Showing Recent Errors Only Build target ImageApp of project ImageApp with configuration Debug CodeSign /Users/carina/Library/Developer/Xcode/DerivedData/ImageApp-braozmttxaqevhglgrebdherlmlh/Build/Intermediates.noindex/Previews/ImageApp/Products/Debug/ImageApp.app (in target 'ImageApp' from project 'ImageApp') cd /Users/carina/Desktop/AME\ 430/ImageApp Signing Identity: "Apple Development: [my email] (B75Q73AMVQ)" /usr/bin/codesign --force --sign 9AFE419D4A362429289B899DECCFB65E5F68E135 -o runtime --entitlements /Users/carina/Library/Developer/Xcode/DerivedData/ImageApp-braozmttxaqevhglgrebdherlmlh/Build/Intermediates.noindex/Previews/ImageApp/Intermediates.noindex/ImageApp.build/Debug/ImageApp.build/ImageApp.app.xcent --timestamp\=none --generate-entitlement-der /Users/carina/Library/Developer/Xcode/DerivedData/ImageApp-braozmttxaqevhglgrebdherlmlh/Build/Intermediates.noindex/Previews/ImageApp/Products/Debug/ImageApp.app /Users/carina/Library/Developer/Xcode/DerivedData/ImageApp-braozmttxaqevhglgrebdherlmlh/Build/Intermediates.noindex/Previews/ImageApp/Products/Debug/ImageApp.app: replacing existing signature /Users/carina/Library/Developer/Xcode/DerivedData/ImageApp-braozmttxaqevhglgrebdherlmlh/Build/Intermediates.noindex/Previews/ImageApp/Products/Debug/ImageApp.app: resource fork, Finder information, or similar detritus not allowed Command CodeSign failed with a nonzero exit code Command CodeSign failed with a nonzero exit code "
1
0
662
Dec ’23
Files locked and cannot make them local to edit
I've pulled the project from Git. Someone else was working on it and it works perfectly fine for them, they can edit all the files. On mine I can only edit what I have added, the files which were already there I can edit, but their changes and additions do not show on the xcode directory on the left side. If i go to finder and click on the project folder there I can see their changes on there.. I tried clicking the lock icon on the preview screen and it says this: “file.swift” is currently locked because it is a remote resource. and when clicking Unlock The file is a remote resource. Try making a local copy. Literally have no idea what to do now. I tried copying their files and making new files and folders like how they made on their branch but it says its already existing even though it is not showing on my swift directory! If you need any other information I am happy to provide it for you!
2
0
1k
Dec ’23
Adding Privacy Manifest to Swift Package
I have gone through (many times) the videos and documentation around adding privacy manifest support to applications and SDKs etc - specifically via the expected PrivacyInfo.xcprivacy file. I am across adding it to the application, and to libraries that produce an xcframework (and signing those etc), however, I also have a series of Swift Package libraries available on GitHub which afaict will also require the privacy info file to declare the libraries privacy related intentions. So my questions are: Where should I add this file within the package setup? Should there be a privacy info file per importable target? Is it expected that the generated privacy report of an application will show info about the library? I have tried within the sources area, and in the root/manifest section, but when I generate a privacy report on the archived application that utilities this library, I can't see any indication that the info is included in the report. This is the generated privacy report from Xcode organiser: My libraries do not actually track or access anything in the required API's list, however I also added some user tracking and linking etc to the privacy info file as a test, and it does not indicate that these are happening in the generated privacy report on the application. Quick example/clarification: I have tried putting the file here: MyPackage - Package.swift > Sources > TargetName - PrivacyInfo.xcprivacy and here MyPackage - Package.swift - PrivacyInfo.xcprivacy > Sources > TargetName If there are docs that I have missed running through this, please link me 😅- I have searched for some clear answers through docs and forum questions but I can't seem to get clarification.
2
1
5.3k
Dec ’23