Post

Replies

Boosts

Views

Activity

KVC / KVO for Operation (Swift 4)
I have created an AsyncOperation which is a subclass of Operation.I am overriding the following methods to use KVC:- isExecuting- isFinishedProblem:When I use String in place of KeyPath, my completion block gets executed. If I use KeyPath the completion block of the operation is not getting executed.Works ok:willChangeValue(forKey: "isExecuting")didChangeValue(forKey: "isExecuting")willChangeValue(forKey: "isFinished")didChangeValue(forKey: "isFinished")Doesn't work (Compiles ok, but at runtime the completion block doesn't get executed):willChangeValue(for: \.isExecuting)didChangeValue(for: \.isExecuting)willChangeValue(for: \.isFinished)didChangeValue(for: \.isFinished)Note: I am using the following:- macOS 10.12.5 (16F73)- Xcode 9.0 beta (9M136h)Questions:1. Why isn't KeyPath working when using the String works ?2. How to fix using KeyPath ?Complete Code:class AsyncOperation : Operation { private var _executing = false private var _finished = false override var isExecuting : Bool { get { return _executing } set { willChangeValue(for: \.isExecuting _executing = newValue didChangeValue(for: \.isExecuting) } } override var isFinished : Bool { get { return _finished } set { willChangeValue(for: \.isFinished) _finished = newValue didChangeValue(for: \.isFinished) } } override var isAsynchronous : Bool { return true } func markAsCompleted() { isExecuting = false isFinished = true } }
8
0
5.1k
Jun ’17
Binding value from an ObservableObject
Aim:I have a model which is an ObservableObject. It has a Bool property, I would like to use this Bool property to initialise a @Binding variable.Questions:How to convert an @ObservableObject to a @Binding ?Is creating a @State the only way to initialise a @Binding ?Note:I do understand I can make use of @ObservedObject / @EnvironmentObject, and I see it's usefulness, but I am not sure a simple button needs to have access to the entire model.Or is my understanding incorrect ?Code:import SwiftUI import Combine import SwiftUI import PlaygroundSupport class Car : ObservableObject { @Published var isReadyForSale = true } struct SaleButton : View { @Binding var isOn : Bool var body: some View { Button(action: { self.isOn.toggle() }) { Text(isOn ? "On" : "Off") } } } let car = Car() //How to convert an ObservableObject to a Binding //Is creating an ObservedObject or EnvironmentObject the only way to handle a Observable Object ? let button = SaleButton(isOn: car.isReadyForSale) //Throws a compilation error and rightly so, but how to pass it as a Binding variable ? PlaygroundPage.current.setLiveView(button)
3
4
23k
Dec ’19
CryptoKit to create JWT
Hi,I would like to create a JWT to interact with Apple's Webservices.As the first step, I have a private key file, I have loaded it as Data.I would like to create an instance of Private Key instance (not sure what is the correct struct to use, tried HMAC, P256.Signing.PrivateKey etc)Every time an exception is thrown.Any help and direction would greatly help. Many thanks.let privateKeyPath = URL(fileURLWithPath: "some valid path") let privateKeyData = try Data(contentsOf: privateKeyPath, options: .alwaysMapped) let message = "abcd" let messageData = message.data(using: .utf8)! do { //Option1: //This throws: Error: incorrectParameterSize let signature1 = try P256.Signing.ECDSASignature(rawRepresentation: privateKeyData) //Option2: let key2 = SymmetricKey(data: privateKeyData) //This throws: Error: incorrectKeySize var encryptedContent2 = try AES.GCM.seal(messageData, using: key2).combined } catch { print("Error: \(error)") }
8
0
4.3k
Feb ’20
Extract Data from P8 file
Hi,I am trying to extract the data from the P8 file to use it generate JWT.I understand that it is possible using dumpasn1 and extracting the OCTET STRING section. This is great, and is definitely possible.I was wondering if it was possible to do it on macOS using Apple's APIs (example SecItemImport), would make it simpler if it was possible all in the mac app.I tried the following but it didn't work:Error: I got the OSStatus as -25257Questions:- Is there a way to do this using SecItemImport or any other Apple APIs as I am using it in a command line mac app ?- Are the parameters to SecItemImport are incorrect ?- Am down the wrong path? , any direction to the correct API would help.What I tried with SecItemImport:- Data extracted from the file- Decoding the data from the file- Some input formatsMany thanks.import Foundation import Security func f1() { do { let fileURL = URL(fileURLWithPath: "some valid path"); let data = try Data(contentsOf: fileURL) guard let string = String(data: data, encoding: .utf8) else { print("Failed to convert data to string") return } let b64Text = string .replacingOccurrences(of: "-----END PRIVATE KEY-----", with: "") .replacingOccurrences(of: "-----BEGIN PRIVATE KEY-----", with: "") .replacingOccurrences(of: "\n", with: "") guard let b64Data = b64Text.data(using: .utf8), let decodedData = Data(base64Encoded: b64Data) else { print("Was not b64 data") return } print(string) var outArray : CFArray? let filename : CFString? = nil var inputFormat = SecExternalFormat.formatUnknown var itemType = SecExternalItemType.itemTypePrivateKey let flags = SecItemImportExportFlags() //I tried data, b64Data, decodedData all seems to return an error let status = SecItemImport(decodedData as CFData, filename, &inputFormat, &itemType, flags, nil, nil, &outArray) //status = -25257 print("status = \(status)") for element in (outArray as [AnyObject]?) ?? [] { print("element = \(element)") } } catch { print("Error: \(error)") } } f1()
4
0
5.1k
Feb ’20
-34018 A required entitlement isn't present
Hi,I have created a new command line tool project, where I am trying to add a key to the keychain.Error:OSStatus: -34018Error Description: A required entitlement isn't present.Questions:1. How can I resolve this error ? I am able to do the same thing using a mac app instead of a command line tool project.2. Am I missing some key steps ?Points to note:- Signing: Automatically manage Signing- Signing certificate - Developmentmain.swiftimport Foundation import CryptoKit func storeKey(label: String) { //Generate key let key = P256.Signing.PrivateKey() let attributes = [kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeyClass: kSecAttrKeyClassPrivate] as [String: Any] // Get a SecKey representation. guard let secKey = SecKeyCreateWithData(key.x963Representation as CFData, attributes as CFDictionary, nil) else { print("Unable to create SecKey representation.") return } let query = [kSecClass: kSecClassKey, kSecAttrApplicationLabel: label, kSecAttrAccessible: kSecAttrAccessibleWhenUnlocked, kSecUseDataProtectionKeychain: true, kSecValueRef: secKey] as [String: Any] // Add the key to the keychain. let status = SecItemAdd(query as CFDictionary, nil) guard status == errSecSuccess else { print("Unable to store item: \(status)") print(SecCopyErrorMessageString(status, nil) ?? "") return } print("successful") } storeKey(label: "TEST-KeyChain-Mac")Attempts made:1. Add Info.plist (contents shown below)2. Add TestExample.entitlements (contents shown below)After adding entitlements I get the following error:Message from debugger: Error 1Program ended with exit code: -1Build Settings Changes:CODE_SIGN_ENTITLEMENTS = TestExample/TestExample.entitlements CODE_SIGN_INJECT_BASE_ENTITLEMENTS INFOPLIST_FILE = TestExample/Info.plist CREATE_INFOPLIST_SECTION_IN_BINARY = YES PRODUCT_BUNDLE_IDENTIFIER = .TestExampleInfo.plist<?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>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> </dict> </plist>TestExample.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>keychain-access-groups</key> <array> <string>$(AppIdentifierPrefix)<same reverse DNS>.TestExample</string> </array> </dict> </plist>
7
0
4.9k
Mar ’20
SwiftUI Observe Changes
Overview:I have a class called Player and a class called Song.Player contains a SongA view is showing the song titleAim:When I change the player.song.title, the view needs to be updated. Problem:When the song's attributes changes, it wouldn't update the view automatically. Only when a new song is assigned will the changes be reflected.My Attempts:I have made 2 attempts (code below), both work as expected.Questions:Is there a better way to do it ? (It seems like a common problem, one would encounter.)Are my attempts reasonable and is attempt 2 better?Or is there something fundamentally flawed with my design? (I was hoping to have the song inside the player because it represented the current song).Original Code (view wouldn't be updated):Modelimport Foundation import Combine class Player : ObservableObject { @Published var duration = 0 @Published var song : Song init(song: Song) { self.song = song } } class Song : ObservableObject { @Published var id : Int @Published var title : String @Published var artist : String init(id: Int, title: String, artist: String) { self.id = id self.title = title self.artist = artist } }View:import SwiftUI struct ContentView: View { @ObservedObject var player : Player var body: some View { VStack { Text(String(player.duration)) Text(player.song.title) Text(player.song.artist) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { let song = Song(id: 1, title: "title1", artist: "artist1") let player = Player(song: song) DispatchQueue.main.asyncAfter(deadline: .now() + 2) { player.song.title = "title2" } return ContentView(player: player) } }Attempt1 - Using CombineLatestProblem: It is not very scalable as the number of properties in a song increases.class Player : ObservableObject { @Published var duration = 0 @Published var song : Song private var songChangeCanceller : AnyCancellable? init(song: Song) { self.song = song songChangeCanceller = song.$title.combineLatest(song.$artist, song.$id).sink { _, _, _ in self.objectWillChange.send() } } }Attemp2: Uses objectWillChange.sinkclass Player : ObservableObject { @Published var duration = 0 @Published var song : Song private var songChangeCanceller : AnyCancellable? private var songAttributesChangeCanceller : AnyCancellable? init(song: Song) { self.song = song songChangeCanceller = $song.sink { newSong in self.songAttributesChangeCanceller = newSong.objectWillChange.sink { _ in self.objectWillChange.send() } } } }
0
0
1.3k
Apr ’20
Revert Xcode Simulator to the default setting
What I had done:I enabled full screen mode on the simulator so I executed the following command:defaults write com.apple.iphonesimulator AllowFullscreenMode -bool YESQuestion:How can I remove this rectangular bar shown in the image (so that it is like the default setting when xcode is installed)?I have tried the following without any success:Executed the above command with a NODeleted /Users/<Username>/Library/Preferences/com.apple.iphonesimulator.plistCreated a new Mac UserDeleted Xcode and installed it again
3
0
1.2k
Apr ’20
How to show alerts one after the other?
Aim I would like to display an alert, when the user dismisses the alert the next alert should be displayed. If the user doesn't dismiss the first alert, the 2nd alert should wait till the user dismisses the first alert Functionality like back pressure. My Attempt: Given below is code where I have attempted to do it based on an @ObservedObject and @Published property. Problem: Alerts are displayed but they don't wait for the alert to be dismissed. Code: ContentView: import SwiftUI struct ContentView: View {     @ObservedObject var model = Model()     var body: some View {         Text("Hello World!")             .alert(item: $model.employee, content: makeAlert(forEmployee:))     }     private func makeAlert(forEmployee employee: Employee) -> Alert {         let dismissButton = Alert.Button.cancel((Text("Ok")))         return Alert(title: Text("New Employee"),                      message: Text(employee.name),                      dismissButton: dismissButton)     } } Model: import Foundation class Model : ObservableObject {     @Published var employee : Employee?     private var index       = 0     private lazy var timer = {         Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { [weak self] timer in             self?.createNewEmployee()             print("fired for \(self?.employee?.name ?? "none")")         }     }()     init() {         timer.fire()     }     func createNewEmployee() {         guard let unicodeScalar = UnicodeScalar(index + 65) else {             return         }         let name = String(Character(unicodeScalar))         employee = Employee(id: index,                             name: name)         index += 1     } } Employee: import Foundation class Employee : Identifiable {     var id : Int     var name : String     init(id: Int, name: String) {         self.id = id         self.name = name     } }
2
0
2.2k
Jun ’20
Swift Concurrency (async let) - Cancellation
I am a bit confused about tasks being cancelled. Overview: checkCancellation function has 2 child tasks: computeA and computeB that run concurrently, computeB throws an error. Doubt: I expected child task computeA to be cancelled because computeB threw an error, but computeA was never cancelled. Is my understanding wrong or am I missing something? Or is this a bug? Note: I am using a SwiftUI project (as Swift Playgrounds don't support async let) macOS Big Sur 11.5.2 (20G95) Xcode Version 13.0 beta 5 (13A5212g) Output: A - started B - going to throw A - going to return, Task.isCancelled = false error: infinity Concurrent Function Definitions: import Foundation import UIKit enum ComputationError: Error { case infinity } fileprivate func computeA() async throws -> Int { print("A - started") await Task.sleep(2 * 100_000_000) print("A - going to return, Task.isCancelled = \(Task.isCancelled)") //I expected Task.isCancelled to be true return 25 } fileprivate func computeB() async throws -> Int { print("B - going to throw") throw ComputationError.infinity } func checkCancellation() async throws { async let a = computeA() async let b = computeB() let c = try await a + b print("c = \(c)") } Invoking Concurrent function struct ContentView: View { var body: some View { Button("check cancellation") { Task { do { try await checkCancellation() print("normal exit") } catch { print("error: \(error)") } } } } }
4
0
1.2k
Aug ’21
@FocusedBinding not working for iOS (using it for Commands)
Aim To use a keyboard shortcut on a Multiplatform app (iOS and macOS) When keyboard shortcut is tapped, the price needs to be printed Problem The same code doesn't work on iPad but works on macOS Question: Why is not working? How to fix this? Environment macOS Big Sur - 11.6 (20G165) Version 13.0 (13A233) Code @main struct TestApp: App { @State private var price = 0 var body: some Scene { WindowGroup { ContentView(price: $price) .focusedValue(\.price, $price) } .commands { PriceCommands() } } } struct ContentView: View { @Binding var price: Int var body: some View { IncreasePriceButton(price: $price) } } struct IncreasePriceButton: View { @Binding var price: Int var body: some View { Button("Increase Price") { price += 1 print("price = \(price)") } } } struct PriceCommandButton: View { @FocusedBinding(\.price) var price var body: some View { Button("Print Price") { print("price = \(price)") } } } struct PriceCommands: Commands { var body: some Commands { CommandMenu("Custom") { PriceCommandButton() .keyboardShortcut(KeyboardShortcut("C", modifiers: [.command, .shift])) } } } struct FocusedPriceKey: FocusedValueKey { typealias Value = Binding<Int> } extension FocusedValues { var price: FocusedPriceKey.Value? { get { self[FocusedPriceKey.self] } set { self[FocusedPriceKey.self] = newValue } } }
1
0
855
Oct ’21
NavigationStack and NavigationSplitView Runtime warnings
Overview: When running the demo code presented in "The SwiftUI cookbook for navigation" (https://developer.apple.com/wwdc22/10054) I ran into some issues: Runtime warnings: 2022-06-08 22:20:31.587169+0800 NavigationSplitViewDemo[17797:672165] [SwiftUI] A NavigationLink is presenting a value of type “Category” but there is no matching navigation destination visible from the location of the link. The link cannot be activated. onChange(of: UpdateTrigger) action tried to update multiple times per frame. 2022-06-08 22:15:23.432289+0800 NavigationSplitViewDemo[17645:662571] [UIFocus] _TtGC7SwiftUI14_UIHostingViewGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__ implements focusItemsInRect: - caching for linear focus movement is limited as long as this view is on screen. Feedback filed: FB10103041 and FB10104196
13
4
7.2k
Jun ’22
Lab appointment - Pending status
Hi, My lab appointment status is pending. The lab is for tomorrow. When would I get to know if my lab appointment has been accepted. It is my first time for a lab appointment, also I forgot to mention the feedback IDs, would there be a way to amend the request to include the feedback IDs if that would help. (Feedback assistant was down when I booked an appointment so couldn't get the feedback IDs.) Any help would be much appreciated as I am from a different timezone and would need to plan accordingly .... really praying I get an appointment
1
0
1k
Jun ’22
Xcode Cloud to use swift 5.7 (Xcode-14)
Overview I have an existing Xcode project that works fine with Xcode Cloud I have a separate branch on to which I have migrated and made changes for Xcode 14 On the same branch I have made some code changes that is supported by Swift 5.7 Example: var price: Int? = 100 guard let price else { return } Problem Xcode code build fails with the error Variable binding in a condition requires an initializer Question: Is it possible to build Xcode Cloud on Swift 5.7 or Xcode 14?
0
0
1k
Jul ’22
Toolbar Menu button seems to look disabled
Overview On macOS, in a NavigationSplitView when the menu button is added to the detail view toolbar, it seems to look disabled Environment Xcode: 14.1 beta 3 (14B5033e) macOS: 13.0 Beta (22A5365d) Code: struct ContentView: View { @State private var selectedNumber: Int? var body: some View { NavigationSplitView { List(0..<100, selection: $selectedNumber) { number in Text("cell \(number)") } } detail: { Text("Detail") .toolbar { ToolbarItem { Menu { Button("aa") {} Button("bb") {} } label: { Label("Add Bookmark", systemImage: "book") } } } } } } Steps to reproduce: Run the project on macOS Select cell 0 on the sidebar Click on the book toolbar button and notice the menu appear Select cell 1 on the sidebar Expected Behaviour After step 4, the book toolbar button should look prominent (like it is enabled) Actual Behaviour After step 4, the book toolbar button looks like it is disabled. Screenshot
1
1
1.5k
Oct ’22