Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

error when trying to decrypt an RSA 2048 encrypted string
Getting the below error when trying to decrypt an encrypted string sent from my server. Printing description of error: ▿ Optional<Unmanaged<CFErrorRef>> ▿ some : Unmanaged<CFErrorRef> - _value : Error Domain=NSOSStatusErrorDomain Code=-50 "<SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, 2048 bits (block size: 256), addr: 0x600000cb16c0>: sign - input buffer bad size (344 bytes)" UserInfo={numberOfErrorsDeep=0, NSDescription=<SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, 2048 bits (block size: 256), addr: 0x600000cb16c0>: sign - input buffer bad size (344 bytes)} I generated the RSA 2048 public private key pairs using private func getRsaKeyPair()->(String,SecKey)?{ let publicKeyAttr: [NSObject: Any] = [ kSecAttrIsPermanent: true, kSecAttrApplicationTag: "com.appname.one.rsa.public".data(using: String.Encoding.utf8)!, kSecClass: kSecClassKey, kSecReturnData: kCFBooleanTrue as Any] let privateKeyAttr: [NSObject: Any] = [ kSecAttrIsPermanent:true, kSecAttrApplicationTag:"com.appname.one.rsa.private".data(using: String.Encoding.utf8)!, kSecClass: kSecClassKey, kSecReturnData: kCFBooleanTrue as Any] var keyPairAttr = [NSObject: Any]() keyPairAttr[kSecAttrKeyType] = kSecAttrKeyTypeRSA keyPairAttr[kSecAttrKeySizeInBits] = 2048 keyPairAttr[kSecPublicKeyAttrs] = publicKeyAttr keyPairAttr[kSecPrivateKeyAttrs] = privateKeyAttr var error: Unmanaged<CFError>? = nil let privateKey = SecKeyCreateRandomKey(keyPairAttr as CFDictionary, &error) if let privateKey { var resultPublicKey: AnyObject? let statusPublicKey = SecItemCopyMatching(publicKeyAttr as CFDictionary, &resultPublicKey) if statusPublicKey == noErr { if let publicKey = resultPublicKey as? Data { return(publicKey.base64EncodedString(), privateKey) } } } return nil } i then sent the public key to my node js server which then returned me a string encrypted with the said public key. I decrypt it as follows guard let key = data.encStr?.data(using: .utf8) else{ return } print("encStr Size: \(key.count) bytes") var error: Unmanaged<CFError>? = nil if let plaintext = SecKeyCreateDecryptedData(privateKey, .rsaEncryptionPKCS1 , key as CFData, &error) as? Data{ print("HURRAY:\(plaintext)") if let plainTextStr = String(data: plaintext, encoding: .utf8){ print(plainTextStr) } }else{ print(error.debugDescription) } But i get the above mentioned error when decrypting using my private key.
1
1
327
Feb ’24
Termination reason: Namespace SIGNAL, Code 11 Segmentation fault: 11
I have Sims 4 downloaded onto my macbook and it has been working just fine until it started closing the application out of nowhere. A full crash report would come up everytime yet I do not understand code and need to know what the issue is. The game opens, and for a few minutes works until it simply closes out of nowhere. Here is the crash report: Crashed Thread: 22 Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x0000000164420150 Exception Codes: 0x0000000000000001, 0x0000000164420150 Termination Reason: Namespace SIGNAL, Code 11 Segmentation fault: 11 Terminating Process: exc handler [1224] VM Region Info: 0x164420150 is not in any region. Bytes after previous region: 344401 Bytes before following region: 18562736 REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL __LINKEDIT 164364000-1643cc000 [ 416K] r--/rw- SM=COW ...thon370.dylib ---> GAP OF 0x1208000 BYTES __TEXT 1655d4000-1655d8000 [ 16K] r-x/rwx SM=COW ...process.dylib Thread 22 Crashed: 0 Simulation.dylib 0x1656e5060 0x16560c000 + 888928 1 Simulation.dylib 0x1656e5144 0x16560c000 + 889156 2 Simulation.dylib 0x165b51274 0x16560c000 + 5526132 3 libsystem_pthread.dylib 0x19152106c _pthread_start + 148 4 libsystem_pthread.dylib 0x19151be2c thread_start + 8 Thread 22 crashed with ARM Thread State (64-bit): x0: 0x0000000000000000 x1: 0xffffffffffffffff x2: 0x0000000000000001 x3: 0x0000000000000001 x4: 0x0000000000000000 x5: 0x0000000001e84800 x6: 0x00000002a84b6af0 x7: 0x0000000170a76778 x8: 0x000000016441ff68 x9: 0x00000001ec891f40 x10: 0x0000000000000011 x11: 0x00000000000002ee x12: 0x0000000000000008 x13: 0x0000000000000004 x14: 0x0000000100000000 x15: 0x0000000000000000 x16: 0x00000001914e274c x17: 0x00000001f16c86e8 x18: 0x0000000000000000 x19: 0x0000000164436620 x20: 0x0000000164436628 x21: 0x0000000164436668 x22: 0x0000000000000002 x23: 0x000000016440fb60 x24: 0x00000001664bce10 x25: 0x00000000db89ff23 x26: 0x00000000811c9dc5 x27: 0x0000000166498000 x28: 0x0000000166498000 fp: 0x0000000170a76f90 lr: 0x11168001656e5144 sp: 0x0000000170a76f40 pc: 0x00000001656e5060 cpsr: 0x60001000 far: 0x0000000164420150 esr: 0x92000007 (Data Abort) byte read Translation fault
1
0
779
Feb ’24
macOS App Launch Fails with RunningBoard Entitlement Errors on WKWebView Video Play
I am developing a macOS application and have encountered an issue with entitlements that I am unable to resolve. The error emerges from the RunningBoard service when I try to play a video in a WKWebView. Here is the specific error: Error acquiring assertion: <Error Domain=RBSServiceErrorDomain Code=1 "(originator doesn't have entitlement com.apple.runningboard.assertions.webkit AND originator doesn't have entitlement com.apple.multitasking.systemappassertions)" UserInfo={NSLocalizedFailureReason=(originator doesn't have entitlement com.apple.runningboard.assertions.webkit AND originator doesn't have entitlement com.apple.multitasking.systemappassertions)}> I'm seeking answers to the following questions: What do the entitlements com.apple.runningboard.assertions.webkit and com.apple.multitasking.systemappassertions refer to specifically? How can I resolve the errors associated with the absence of these entitlements? This problem appears to affect many users, yet a public solution has not been identified. I've tried adding NSMicrophoneUsageDescription and NSCameraUsageDescription to my Info.plist, as suggested here, but to no avail. An apparent Apple employee suggested adding Background Modes to capabilities here, but such options do not exist. Numerous similar issues are documented online, but none provide a resolution. When I attempt to include the entitlements com.apple.runningboard.assertions.webkit and com.apple.multitasking.systemappassertions as indicated in the logs, my application fails to start, resulting in the following error message: Could not launch “My App Name” Runningboard has returned error 5. Please check the system logs for the underlying cause of the error. The error logs are extensive and include: Could not launch “Quick Music Bar” Domain: IDELaunchErrorDomain Code: 20 Recovery Suggestion: Runningboard has returned error 5. Please check the system logs for the underlying cause of the error. User Info: { DVTErrorCreationDateKey = "2024-02-24 06:26:22 +0000"; DVTRadarComponentKey = 968756; IDERunOperationFailingWorker = IDELaunchServicesLauncher; } -- The operation couldn’t be completed. Launch failed. Domain: RBSRequestErrorDomain Code: 5 Failure Reason: Launch failed. -- Launchd job spawn failed Domain: NSPOSIXErrorDomain Code: 153 -- Event Metadata: com.apple.dt.IDERunOperationWorkerFinished : { "device_model" = "Mac14,10"; "device_osBuild" = "14.3.1 (23D60)"; "device_platform" = "com.apple.platform.macosx"; "dvt_coredevice_version" = "355.7.7"; "dvt_mobiledevice_version" = "1643.60.2"; "launchSession_schemeCommand" = Run; "launchSession_state" = 1; "launchSession_targetArch" = arm64; "operation_duration_ms" = 113; "operation_errorCode" = 20; "operation_errorDomain" = IDELaunchErrorDomain; "operation_errorWorker" = IDELaunchServicesLauncher; "operation_name" = IDERunOperationWorkerGroup; "param_debugger_attachToExtensions" = 0; "param_debugger_attachToXPC" = 1; "param_debugger_type" = 3; "param_destination_isProxy" = 0; "param_destination_platform" = "com.apple.platform.macosx"; "param_diag_MainThreadChecker_stopOnIssue" = 0; "param_diag_MallocStackLogging_enableDuringAttach" = 0; "param_diag_MallocStackLogging_enableForXPC" = 1; "param_diag_allowLocationSimulation" = 1; "param_diag_checker_tpc_enable" = 1; "param_diag_gpu_frameCapture_enable" = 0; "param_diag_gpu_shaderValidation_enable" = 0; "param_diag_gpu_validation_enable" = 0; "param_diag_memoryGraphOnResourceException" = 0; "param_diag_queueDebugging_enable" = 1; "param_diag_runtimeProfile_generate" = 0; "param_diag_sanitizer_asan_enable" = 0; "param_diag_sanitizer_tsan_enable" = 0; "param_diag_sanitizer_tsan_stopOnIssue" = 0; "param_diag_sanitizer_ubsan_stopOnIssue" = 0; "param_diag_showNonLocalizedStrings" = 0; "param_diag_viewDebugging_enabled" = 1; "param_diag_viewDebugging_insertDylibOnLaunch" = 1; "param_install_style" = 0; "param_launcher_UID" = 2; "param_launcher_allowDeviceSensorReplayData" = 0; "param_launcher_kind" = 0; "param_launcher_style" = 99; "param_launcher_substyle" = 8192; "param_runnable_appExtensionHostRunMode" = 0; "param_runnable_productType" = "com.apple.product-type.application"; "param_structuredConsoleMode" = 1; "param_testing_launchedForTesting" = 0; "param_testing_suppressSimulatorApp" = 0; "param_testing_usingCLI" = 0; "sdk_canonicalName" = "macosx14.2"; "sdk_osVersion" = "14.2"; "sdk_variant" = macos; } -- System Information macOS Version 14.3.1 (Build 23D60) Xcode 15.2 (22503) (Build 15C500b) Timestamp: 2024-02-24T15:26:22+09:00 The system information is as follows: macOS Version 14.3.1 (Build 23D60), Xcode 15.2 (22503) (Build 15C500b), Timestamp: 2024-02-24T15:26:22+09:00 Has anyone else encountered this issue, or can anyone provide guidance on how to proceed?
1
0
778
Feb ’24
Swift TableView: Saving Text from TextField
For the past few months, I’ve been learning about Swift coding. I’m relatively new to the coding field so this may seem trivial to some. Here’s what I’m trying to do: I cannot get the data saved from regular textboxes to appear in the table I've designed on the storyboard. It is clearly saving something to the table rows but I cannot see it. I've looked all over the web but most examples are from old versions of swift/deprecated versions of Xcode and are not applicable. Basically, I’m designing an app for my company that allows quick and easy saving of users that call; I would be able to save their company, name, phone, userid, etc, the app saves it into the table And allows me to reference it later. I'm using core data and I’ve attached all of the code to the appropriate storyboard fields. any insight or errors someone could point out would be very helpful. Here’s my code: import Cocoa import SwiftData import SwiftUI class User: NSManagedObject, Identifiable { let id = UUID() //compatibility @NSManaged public var company: String @NSManaged public var name: String @NSManaged public var phone: String @NSManaged public var uid: String @NSManaged public var cid: String @NSManaged public var tvid: String @NSManaged public var tvpwd: String @NSManaged public var notes: String } class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate { @IBOutlet weak var companyTextField: NSTextField! @IBOutlet weak var nameTextField: NSTextField! @IBOutlet weak var phoneTextField: NSTextField! @IBOutlet weak var uidTextField: NSTextField! @IBOutlet weak var cidTextField: NSTextField! @IBOutlet weak var tvidTextField: NSTextField! @IBOutlet weak var tvpwdTextField: NSTextField! @IBOutlet weak var notesTextField: NSTextField! @IBOutlet weak var tableView: NSTableView! var users = [User]() override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self } @IBAction func saveButtonClicked(_ sender: NSButton) { let user = User() users.append(user) tableView.reloadData() } // MARK: - NSTableViewDataSource func numberOfRows(in tableView: NSTableView) -> Int { return users.count } // MARK: - NSTableViewDelegate func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let user = users[row] guard let cell = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: self) as? NSTableCellView else { return nil } switch tableColumn?.identifier.rawValue { case "company": cell.textField?.stringValue = user.company case "name": cell.textField?.stringValue = user.name case "phone": cell.textField?.stringValue = user.phone case "uid": cell.textField?.stringValue = user.uid case "cid": cell.textField?.stringValue = user.cid case "tvid": cell.textField?.stringValue = user.tvid case "tvpwd": cell.textField?.stringValue = user.tvpwd case "notes": cell.textField?.stringValue = user.notes default: return nil } return cell } } ![]
2
0
500
Feb ’24
[iOS12.5] UITabBarItem selectedImage not working
Hi everyone, I'm having issue with UITabBarItem's selectedImage is not working only on iOS 12. Image is in PNG format, already tried with PDF single scale but result still the same. let vc = HomeViewController.storyboardInstance() let tabBarItem = UITabBarItem(title: "home".localized(), image: UIImage(named: "tabbar.home.selected"), selectedImage: UIImage(named: "tabbar.home.selected")) tabBarItem.updateFont() vc.tabBarItem = tabBarItem return CustomNavigationController(rootViewController: vc) I also want to mention that image is working fine with original color (render as Original Image) but selectedImage (render as Original Image) with original color doesn't work. Does anyone here know what is the problem ?
0
0
218
Feb ’24
How can I reverse USDZ animation in realityKit
How can i play a USDZ entity animation in reverse? I have tried to put a negative value to the speed as I was doing in SceneKit to make the animation reverse play but it did not work. here is my code: import SwiftUI import RealityKit struct ImmersiveView: View { @State var entity = Entity() @State var openDoor: Bool = true var body: some View { RealityView { content in if let mainDoor = try? await Entity(named: "Door.usdz") { if let frame = mainDoor.findEntity(named: "DoorFrame") { frame.position = [0, 0, -8] frame.orientation = simd_quatf(angle: (270 * (.pi / 180)), axis: SIMD3(x: 1, y: 0, z: 0)) content.add(frame) entity = frame.findEntity(named: "Door")! entity.components.set(InputTargetComponent(allowedInputTypes: .indirect)) entity.components.set(HoverEffectComponent()) let entityModel = entity.children[0] entityModel.generateCollisionShapes(recursive: true) } } } .gesture( SpatialTapGesture() .targetedToEntity(entity) .onEnded { value in print(value) if openDoor == true { let animController = entity.playAnimation(entity.availableAnimations[0], transitionDuration: 0 , startsPaused: true) animController.speed = 1.0 animController.resume() openDoor = false } else { let animController = entity.playAnimation(entity.availableAnimations[0], transitionDuration: 0 , startsPaused: true) animController.speed = -1.0 // it does not work to reverse animController.resume() openDoor = true } } ) } } The Door should open with first click which is already happening and close with second click which is not happening as it does not reverse play the animation
5
0
772
Mar ’24
Error Domain=NSCocoaErrorDomain Code=257
Hello, I have created a documentspicker to select a PDF file and then upload it to storage, but I am getting this error only on my device; it works correctly on the simulator. This is my code: @Binding var alertShow:Bool var detailpet:String = "" func makeCoordinator() -> Coordinator { return DocumentPicker.Coordinator(parent1: self) } func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentPicker>) -> UIDocumentPickerViewController { let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.pdf]) picker.allowsMultipleSelection = false picker.delegate = context.coordinator return picker } func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: UIViewControllerRepresentableContext<DocumentPicker>) { } class Coordinator : NSObject, UIDocumentPickerDelegate { var parent:DocumentPicker init(parent1: DocumentPicker){ parent = parent1 } func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls:[URL]) { let bucket = Storage.storage().reference() let db = Firestore.firestore() let collection = "documents" guard let url = urls.first, url.startAccessingSecurityScopedResource() else { return } DispatchQueue.main.async { url.stopAccessingSecurityScopedResource() print("Documents Picker stop") } let referenceDocument = bucket.child("docu/\(url.deletingPathExtension().lastPathComponent)") let _ = referenceDocument.putFile(from:url, metadata: nil) { metadata , error in guard metadata != nil else{ print("Error \(String(describing: error?.localizedDescription))") return } referenceDocument.downloadURL { url, error in guard let url = url else { print("Message error \(String(describing: error?.localizedDescription))") return } let _ = try? db.collection(collection).addDocument(from:DocumentData(idpet:self.parent.detailpet, name: "\(url.deletingPathExtension().lastPathComponent).pdf", url: url.absoluteString)) } print("Succes") self.parent.alertShow.toggle() } } } } t seems to be a permissions issue, I believe. Do you know how I can fix this? It's my first application. Thank you.
1
0
281
Feb ’24
AVAudioRecorder currentTime different than AVPlayer.duration
I have a small audio app that records audio and then the user can play back. I am having an issue trying to display elapsed and total times. When I record the file, I use the audiorecorder.currentTime to get the recording length but when I load it in AVPlayer, it shows a different length. It is usually around 200ms off but not always. When comparing the raw files. the AVPlayer does seem to report the correct time (length). I am using a timer when recording that fires every 100ms since I don't think AVAudioRecorder has an observer like the AVPlayer, that updates the recording time using the audiorecorder.currentTime. I've checked out a number of things online and all of the example code I've found seems to have the same issue with the recorded time and player duration not being the same (The examples I have show the recorded time but never show the playback length but I manually loaded the file to check the playback length and it was always longer than the recorded display length) but there has to be a way to do this properly? Hopefully someone has some ideas or can tell me of a way they worked around this. I am recording using the following settings; let settings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 16000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ]
0
0
305
Feb ’24
local doc save and iCloud data in same app
I have app that is using container for small settings data and iCloud for larger storage, but I also want to be able to save to local documents folder. When I do that the url that is created is not local docs, but: path: file:///var/mobile/Containers/Data/Application/85A8B8C9-C0C3-4843-A74C-5A951F593790/Documents/Dialog08:45,%2022%20Feb%202024 Here is code using to save to local docs folder. func saveDataToFile(data: String) { //file will be datetimedialog let formatter = DateFormatter() formatter.dateFormat = "HH:mm, d MMM y" var dateTime = Date.getCurrentDate() dateTime = formatter.string(from: Date.now) var saveFilename = "Dialog" saveFilename.append(dateTime) let path = getDocumentsDirectory().appendingPathComponent(saveFilename) print("path: \(path)") // let fileURL = URL(fileURLWithPath: data, relativeTo: path) do { try data.write(to: path, atomically: true, encoding: String.Encoding.utf8) } catch { print(error.localizedDescription) } } func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return paths[0] }
1
0
399
Feb ’24
SPM show-dependencies broken
I have a Package.swift // swift-tools-version: 5.9 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "SharedUI", defaultLocalization: "en_US", platforms: [.iOS(.v16)], products: [ .library( name: "SharedUI", targets: [ "AppTheme", ] ), ], dependencies: [ .package(url: "https://github.com/apple/swift-markdown.git", "0.2.0"..<"0.3.0"), ], targets: [ .target( name: "AppTheme", dependencies: [ .product(name: "Markdown", package: "swift-markdown"), ], path: "AppTheme" ), ] ) Run swift package show-dependencies shows error yuantong-macbookpro2:Downloads yuantong$ swift package show-dependencies Fetching https://github.com/apple/swift-markdown.git from cache Fetched https://github.com/apple/swift-markdown.git (0.67s) error: Couldn’t get the list of tags: fatal: cannot use bare repository '/Users/yuantong/Downloads/.build/repositories/swift-markdown-b692ce3c' (safe.bareRepository is 'explicit') which I think used to work before Xcode 15.
0
0
309
Feb ’24
Xcode "Build documentation" not working with Swift Macro package in project
I have a workspace with my project and a Swift Macro. When I use the "Build Documentation" command the build fails with this error: fatal error: module map file '/Users/me/Library/Developer/Xcode/DerivedData/Project-fmdkuqlofexbqdhhitpgjnoqzyrz/Build/Intermediates.noindex/GeneratedModuleMaps-iphoneos/Macros.modulemap' not found Is there a way around this?
0
0
487
Feb ’24
My app was rejected because it offers repair services for mobile devices not produced by Apple
Hello, My app was rejected because it offers repair services for mobile devices not produced by Apple. Could any body explain to me what's the problem here and how can I avoid app rejection due to it. My app is selling mobile spare parts for all kinds of mobiles it doesn't provide any kind of repair services, it just sell mobile spare parts and mobile maintenance tools like tweezers, does the problem is with maintenance tools?! This is apple rejection message: Guideline 2.3.10 - Performance - Accurate Metadata We noticed that your app includes functionality that isn't focused on the iPhone, iPad, Mac, Apple TV, or Apple Watch experience. Specifically, your app offers repair services for mobile devices not produced by Apple, which is not appropriate for the App Store.
2
0
269
Feb ’24