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

Swift Documentation

Pinned Posts

Posts under Swift tag

2,257 Posts
Sort by:
Post not yet marked as solved
1 Replies
136 Views
I have installed the latest beta on my iPad , iPadOS 16.1 (20B5050f) On running in app in Playgrounds that has a TextField, external keyboard input do not seem to be working. Tapping on the Text field inserts the cursor but no text can be entered on my external keyboard. (TextEditor field also do not work) Tested with both a Smart Keyboard and a Magic Keyboard. The keyboard works to enter the code in playgrounds, so it is not a keyboard connection issue. Disconnecting the keyboard, the onscreen keyboard is displayed and works correctly. Is this a Playgrounds issue or an iPadOS 16.1 issue or a compatibility issue with Playgrounds & iPadOS 16.1 ? import SwiftUI struct ContentView: View {     @State var field: String = "Test input"          var body: some View {         VStack {             Image(systemName: "globe")                 .imageScale(.large)                 .foregroundColor(.accentColor)             Text("Hello, world!")             TextField("", text: $field)                 .frame(height: 100)         }     } }
Posted
by PhilB.
Last updated
.
Post not yet marked as solved
0 Replies
5 Views
Despite finally adding this modifier, it appears that Apple neglected to provide a way to react to the preview view being tapped. I'm hoping I'm just overlooking it. Is anyone aware of a way to handle the context menu's preview view being tapped?
Posted
by tundaware.
Last updated
.
Post marked as solved
1 Replies
30 Views
I have two apps, both made on iPad with Swift Playgrounds 4. The newer one was made with the latest release of SP4 and thus uses Swift 5.6, the other uses Swift 5.5 because it was made with a former version of SP4. iPadOS is 15.7. Both apps make use of a Settings.bundle and both use the same code to register. @main struct MyApp: App { init() { if !UserDefaults.standard.bool(forKey: "launchedBefore") { registerDefaultSettings() let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] let build = Bundle.main.infoDictionary?["CFBundleVersion"] let versionInfo = "\(version!) (\(build!))" UserDefaults.standard.set( versionInfo, forKey: "versionInfo") UserDefaults.standard.set(true, forKey: "launchedBefore") } } var body: some Scene { WindowGroup { ContentView() } } } private func registerDefaultSettings() { guard let settingsBundle = Bundle.main.url(forResource: "Root.plist", withExtension: nil), let settings = NSDictionary(contentsOf: settingsBundle), let keyValues = settings.object(forKey: "PreferenceSpecifiers") as? [[String: AnyObject]] else { return } var defaultSettings = [String : AnyObject]() for keyValue in keyValues { if let key = keyValue["Key"] as? String, let value = keyValue["DefaultValue"] { defaultSettings[key] = value } } UserDefaults.standard.register(defaults: defaultSettings) } The settings of the 5.5 app appear in the Settings App whereas the settings of the 5.6 do not. If I move the Settings.bundle folder from 5.6. to 5.5, the settings for 5.6 appear in 5.5 thus the file structure and contents seem to be syntactically ok). There was one obvious difference when setting up Settings.bundle in 5.6: SP4 requested to set defaultLocalization in Package.swift. How do I get the 5.6 Settings.bundle to appear in the Settings App?
Posted Last updated
.
Post not yet marked as solved
1 Replies
28 Views
Hello! I can't understand what am I supposed to do in this exercise. Can someone walk me through? Exercise: Leap Years To decide if a year is a leap year, there are several decisions that have to be made in the correct order. Is the year divisible by 4? If so, is the year divisible by 100? If so, is the year divisible by 400? If so, it is a leap year. If not, it is not a leap year. If it's not divisible by 100, it is a leap year. If it's not divisible by 4, it is not a leap year. These decisions can be made inside a function as a series of nested if...else statements. The number(_:, isDivisibleBy:) function has been built into this playground to make this exercise easier. Below is an incomplete function for deciding if a given year is a leap year: func isLeapYear(_ year: Int) -> Bool {     // Is the year divisible by 4?     if number(year, isDivisibleBy: 4) {         return true     } else {         return false      } // Should be true isLeapYear(2000) // Should be false isLeapYear(1900) // Should be true isLeapYear(2012) // Should be false isLeapYear(2017) Exercise Complete the function above so that the rules are all followed and the examples get the correct answers.  Hint: Try using the rules as pseudocode by making them into comments. Then write the code that goes with each comment underneath it. Exercise For a challenge, complete the function below. It should behave identically without using any nested conditional statements. Use a single level of if/else statements along with conditionals that use Boolean operators.  Hint: Create constants that represent the three key conditions, and then compose a Boolean expression with those constants. func isLeapYear2(_ year: Int) -> Bool { }
Posted Last updated
.
Post not yet marked as solved
40 Replies
9.6k Views
I'm seeing a runtime warning in Xcode 14 Beta 5 that says "This method should not be called on the main thread as it may lead to UI unresponsiveness." This is happening on the @main entry point of my app. See below: The warning shown gives me no insight into what's actually going wrong. I think it may be due to some Core Location code that runs when the app first opens, but is there a way for me to get some more insight into what's causing this? Or is this possibly an Xcode 14/iOS 16 bug, and this is not an issue to worry about? I'm not getting any warnings on Xcode 13/iOS 15.
Posted
by r.token.
Last updated
.
Post marked as solved
3 Replies
41 Views
Hi, I'm trying to create a Tabular experience where the user can select a row and a cell at the same time. To give a better understanding, consider the following image: Here, the user has selected the row containing "Data 1a, Data 2a, Data 3a, Data 4a". At the same time, their cursor is on the cell containing "Data 1a". When the user presses the Right arrow key, the row continues to be selected, but the cell selection should move to the cell containing "Data 2a". On the same front, when the user is on "Data 4a" and presses the right arrow key, the row selection moves to the next one(containing the 'b' suffixed data) while the cell containing "Data 1b" should get selected. How can this experience be achieved using NSTableView?
Posted Last updated
.
Post not yet marked as solved
0 Replies
26 Views
I have not seen a tutorial that shows a callout when a marker is clicked in the map. Can anyone please confirm? Weird that this feature is not included. The callout I need is just a simple title and subtitle. That's all. Tutorials only show how to render using MapMarker, MapPin and custom MapAnnotations but these do nothing since they only show icons.
Posted
by chitgoks.
Last updated
.
Post not yet marked as solved
1 Replies
59 Views
I have 2 apps, I use HMAC for signature between apps. First App's minimum deployment target is 11.2 and it uses CryptoSwift for sending data to the second app while signing documents. But the Second app uses Apple's CryptoKit, and I get a signing error. Can I use different packages for HMAC Sha256 process?
Posted
by Kanan27.
Last updated
.
Post not yet marked as solved
1 Replies
24 Views
Hi, I am facing issues extracting system certificates/identity on an iOS device. I am using the following code to get all identities from my system keychain ( not the app level keychain)         let getquery = [kSecMatchLimit: kSecMatchLimitAll,                              kSecReturnRef: true,                              kSecClass: kSecClassIdentity] as CFDictionary         var item: CFTypeRef?         let status = SecItemCopyMatching(getquery, &item)         guard status != errSecSuccess else {             let key = item as! SecKey             print(key)             return;         } This works if I run this for MacOS as target platform but returns -25300 for my iOS app. I have the same identities/certificates installed. For iOS it is at “general->VPN and device management->Configuration profiles->{profile name} (which shows “contains: Certificate”} and for MacOS it is at “Keychain Access”. How I downloaded the certificates: visited the site on my browser and downloaded it through safari, in settings verified it using passwords. So I didn’t download it from code. Do I have to add some permission in info.plist or something. I didn’t add it for the MacOS app. Or is this even possible, with all the sandbox features and how iOS app were not able to access keychain items before. But I couldn’t find anything as such about this issue and it looks like it is possible. I also tried another query which again worked on my MacOS target platform and gave me all certificates from system keychain       let dic : NSDictionary = [kSecMatchLimit: kSecMatchLimitAll,                                 kSecReturnAttributes: kCFBooleanTrue!,                                 kSecReturnRef: kCFBooleanTrue!,                                 kSecClass: kSecClassCertificate]       var result : CFTypeRef?       let resultCode : OSStatus = SecItemCopyMatching(dic, &result)       if resultCode == errSecSuccess { print(result) } I also looked at https://developer.apple.com/library/archive/qa/qa1745/_index.html for some reference. I didn’t get the part of "reading in a PKCS#12-formatted blob and then importing the contents of the blob into the app's keychain using the function SecPKCS12Import”. If I can get any example of reading in a PKCS#12 blob that’d be very helpful as well. Thanks.
Posted Last updated
.
Post not yet marked as solved
1 Replies
69 Views
Hi guys, I don't know if it's something in my code or a bug but for some reason on my latest project tableView.indexPathForRow(at: to:) is returning an index that is off by one. I have a stripped down tableview controller with a custom cell and button linked to the "testButton" method. I also tagged the button with the indexPath.row from the cellForRowAt method so I know the cell is in the correct place. The problem is, in tableView.indexPathForRow, the tag shows up with the expected value, but the indexPath.row from that method is off by one. class TestListViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() configureTableView() } } extension TestListViewController { private func configureTableView() { tableView.register(TestCell.self, forCellReuseIdentifier: "TestCell") } @objc func testButton(_ sender: UIButton) { guard let indexPath = tableView.indexPathForRow(at: sender.convert(CGPoint.zero, to: self.tableView)) else { return } print("Tag: \(sender.tag)") //This comes up as expected and the tag matches the row print("IndexPath: \(indexPath)") //This does not, index row is off by one! } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TestCell", for: indexPath) as! TestCell cell.nameLabel.text = "Row \(indexPath.row)" cell.checkbox.addTarget(self, action: #selector(testButton(_ :)), for: .touchUpInside) cell.checkbox.tag = indexPath.row return cell } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 50 } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } } In my actual app there is a checkbox on each cell and if I tap the first cells checkbox obviously the app crashes because the index is out of range, if I tap the second cells checkbox, the first cells checkbox fills in. I'm at an utter loss, I have used this method many times in production apps just fine so I'm hoping it's just something I'm forgetting to do.
Posted
by SN81.
Last updated
.
Post not yet marked as solved
5 Replies
826 Views
We have a binary framework built with Xcode 13.0 with module stability (BUILD_LIBRARY_FOR_DISTRIBUTION) enabled. As such, the framework can be used on all versions of Xcode 13.x. When using the same binary framework in Xcode 14.0 beta (14A5228q), we get the following error and the app doesn't compile: Failed to build module 'OurFramework'; this SDK is not supported by the compiler (the SDK is built with 'Apple Swift version 5.5 (swiftlang-1300.0.31.1 clang-1300.0.29.1)', while this compiler is 'Apple Swift version 5.7 (swiftlang-5.7.0.113.202 clang-1400.0.16.2)'). Please select a toolchain which matches the SDK. Is there a change to how module stability works in Xcode 14, or is this a temporary limitation (or bug) in Xcode 14.0 beta that will be addressed in future updates?
Posted Last updated
.
Post not yet marked as solved
1 Replies
338 Views
HI, I have archived CoreML model and deployed it in CoreML Model deployment. If I try to access it in app, facing issue like "Failed to begin access for model collection with identifier". I have double checked the identifiers in my app and CoreML model deployment, both are same. Not sure what mistake I'm making, Thanks in advance. Please view my code used in Xcode as below: func asddasd() {       if #available(iOS 14.0, *) {         let progress = MLModelCollection.beginAccessing(identifier: "MainCoreMLCollection", completionHandler: modelCollectionAvailable)         debugPrint(progress)       } else {         // Fallback on earlier versions       }     }           @available(iOS 14.0, *)     func modelCollectionAvailable(result: Result<MLModelCollection, Error>) {       switch result {       case .success(let collection):         debugPrint("Model collection \(collection.identifier) is now available.")                   // Load a model from the collection.         loadModel("BCGSearchClassifier", from: collection)                 case .failure(let error):         debugPrint("Error accessing a model collection: \(error)")       }     }           @available(iOS 14.0, *)     func loadModel(_ modelName: String, from collection: MLModelCollection) {       debugPrint(collection.entries[modelName])       guard let entry = collection.entries[modelName] else {         debugPrint("Couldn't find model \(modelName) in \(collection.identifier).")         return       }       MLModel.load(contentsOf: entry.modelURL) { result in         switch result {         case .success(let modelFromCollection):           // Use the modelFromCollection instance.         debugPrint("success")           debugPrint(modelFromCollection)         case .failure(let error):           debugPrint("Error loading model \(modelName) in \(collection.identifier): \(error).")         }       }     } ERROR: MLModelCollection: namespace (TeamID.BCGCoreMLCollection) download failed. Error Domain=com.apple.trial Code=0 "Unknown error." UserInfo={NSLocalizedDescription=Unknown error.} Error Domain=com.apple.CoreML Code=10 \"Failed to begin access for model collection with identifier \'MainCoreMLCollection\': invalid identifier\" UserInfo={NSLocalizedDescription=Failed to begin access for model collection with identifier \'MainCoreMLCollection\': invalid identifier}"
Posted
by ragulml03.
Last updated
.
Post not yet marked as solved
1 Replies
39 Views
@StateObject private var vm = QuotesViewModelImpl(service: QuotesServiceImpl()) --> Error Here          var body: some View {         Group {             if vm.quotes.isEmpty {                 LoadingView(text: "Fetching Quotes")             } else {                 List {                     ForEach(vm.quotes, id: \.anime) { quote in                         QuoteView(quote: quote)                     }                 }             }         }         .task {             await vm.getRandomQuotes()         }     }     } Here is the ViewModel: final class QuotesViewModelImpl: QuotesViewModel {     @Published private(set) var quotes: [Quote] = []     private let service: QuotesService     init(service: QuotesService) async {         self.service = service     }     func getRandomQuotes() async {         do {             self.quotes = try await service.fetchRandomQuotes()         } catch {             print(error)         }     } }
Posted
by Abdo23.
Last updated
.
Post not yet marked as solved
0 Replies
24 Views
I am working on apple sign-in implementation. I have added all requirement to require for apple sign-in. But there is issue after click on continue, showing the error sign-up not completed. One more thing I have added two bundle id with different account. one account is working fine and another one is not. is this developer account issue? Please suggest Thanks
Posted Last updated
.
Post not yet marked as solved
2 Replies
276 Views
Hi, all I developed an APP using Share Extension to import String from txt file into CoreData and synced by iCloud. In the test of Simulator or device, the Share Extension will success once in about two or three trials. When I test it in TestFlight, the Share Extension almost not work. After I import the same file 10 times continuously, waiting about 30 minutes, one or two files may be imported successfully. And the one or two files being successfully imported to CoreData are all created in a same time when I check them in CloudKit DashBoard. How to improve the success rate of Share Extension in Simulator and TestFlight? Thanks.
Posted
by poew152.
Last updated
.
Post not yet marked as solved
1 Replies
407 Views
Hi all, I'm struggling with a pretty strange problem and I can't find a solution on how to fix this. Basically if I add a UIView as header of a UITableView with large titles enabled, the large title starts collapsed and is not large by default. In all others cases, when I push a view controller with a UITableView without the header view, the large title starts large as I wish. My desired large title behaviour is to see it large also here when I push this view. What I'm doing wrong on? Thank you in advance. I've attached some screenshots from Storyboard (already from here you can see that the large title gets smaller as soon as I add the view as header) and also a screen from the running app. Storyboard screens: First opening on running app (it starts collapsed): After scrolling it enlarge correctly: PS: I've also found this question on StackOverflow with the same problem of mine, but with no useful answers. https://stackoverflow.com/questions/59263994/swift-preferslargetitles-not-working-if-there-is-a-headerview-in-tableview
Posted Last updated
.
Post not yet marked as solved
1 Replies
84 Views
We are seeing a strange behaviour where the maximum MTU size sent from the phone to our peripheral has decreased from 185 (iOS 15) to 77 (iOS 16 and 16.0.2). We are seeing the exact same behaviour on iPhone 11, iPhone 13 Pro Max and iPhone 14. The source code for the iOS app has not changed at all, yet for some reason the MTU seems to significantally decrease after upgrading to iOS 16. Below is a sniffer log showing how on iOS 15.7 (19H12) running on an iPhone 7, the iPhone's requested MTU is 185 bytes:- And the sniffer log below shows how on iOS 16.0.2 running on iPhone 13 Pro Max, the iPhone's requested MTU is only 77 bytes:- The sudden decrease in the iOS's MTU size is forcing the app to resort to long writes instead of normal writes (when attempting to write to a characteristic larger than 77 bytes), which is causing the interaction to break. Any idea if this is a known bug on iOS 16? And is there a fix/workaround on the app side that can revert the behaviour so that the phone requests 185 bytes? Thanks
Posted Last updated
.
Post not yet marked as solved
0 Replies
22 Views
Learn to code 1 module is not showing the puzzle on the right viewport. I can write commands and run them, but the puzzle viewport is just blue. Skipping through the lessons I can get maybe 5 of the puzzles to show up. When loading the puzzle viewport, playgrounds will automatically try to run code and fail. On the puzzles that show up, it won't try to run code after the initial loading. And the puzzle works just fine. Playgrounds V14.1 MacBook Pro 13-inch Late 2013 model Big Sur OS
Posted Last updated
.
Post not yet marked as solved
2 Replies
303 Views
I have a feature in my app which is very similar to native Clock alarms, where users can set a time for a reminder and optional days of the week to repeat the reminder. Example Case User sets a reminder at 1:00 PM, repeating every day. I schedule 7 notifications, 1 for each weekday, each repeating. The user should get a notification every day at 1:00 PM unless they turn off the feature. Problem After successfully scheduling local notifications, and it working for the first day, the notifications stop working and printing pending notifications shows that they mysteriously got unscheduled. What I know I've heard of a 64 limit to notifications, but when testing with 7 notifications (1 reminder for each day of the week, repeating) it doesn't work either. Each notification has an ID in the format: <my bundle id>.<UUIDstring> It consistently works on the first day, then fails on the 2nd or 3rd day The app is in production, the problem occurs in both development and production environments. Code for day in self.days { /* days is an array of integers representing weekdays */ let content = UNMutableNotificationContent() content.title = "Practice \(profile.name)" content.categoryIdentifier = "reminder" content.sound = UNNotificationSound.default var dateComponents = DateComponents() dateComponents.weekday = day dateComponents.hour = Calendar.current.component(.hour, from: self.date) dateComponents.minute = Calendar.current.component(.minute, from: self.date) dateComponents.second = 0 let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) /* id(for:) generates a unique id using a UUID and the weekday. */ let request = UNNotificationRequest(identifier: id(for: day), content: content, trigger: trigger) center.add(request) { (error) in print(error) /*never an error here*/ } } The code seems to work exactly as intended; printing pending notifications shows 7 repeating notifications on different days as expected. However after a few days it stops working, and printing pending notifications shows no pending notifications. I really need to get this resolved. Any ideas?
Posted
by MilesV64.
Last updated
.
Post not yet marked as solved
2 Replies
181 Views
Hello everyone! I am trying to create a spectrogram like in the attached image for a macOs App. I am using Cocoa/AppKit but also have some SwiftUI views, so I can use either. I have found the sample app Visualizing Sound as an Audio Spectogram that apple provides but I do not want a real-time spectrogram. I want a spectrogram of the whole audio file. I have been trying to convert the sample app to what I need but I have been unsuccessful so far. Here is how I changed the code in the delegate public func captureBuffer() { let asset = AVAsset(url: audioFileUrl) let reader = try! AVAssetReader(asset: asset) let track = asset.tracks(withMediaType: AVMediaType.audio)[0] let settings = [ AVFormatIDKey : kAudioFormatLinearPCM ] let readerOutput = AVAssetReaderTrackOutput(track: track, outputSettings: settings) reader.add(readerOutput) reader.startReading() while let buffer = readerOutput.copyNextSampleBuffer() {   var audioBufferList = AudioBufferList(mNumberBuffers: 1, mBuffers: AudioBuffer(mNumberChannels: 0, mDataByteSize: 0, mData: nil))   var blockBuffer: CMBlockBuffer?   CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer( buffer, bufferListSizeNeededOut: nil, bufferListOut: &audioBufferList, bufferListSize:  MemoryLayout<AudioBufferList>.size, blockBufferAllocator: nil, blockBufferMemoryAllocator: nil, flags: kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, blockBufferOut: &blockBuffer   ); let buffers = UnsafeBufferPointer<AudioBuffer>(start: &audioBufferList.mBuffers, count: Int(audioBufferList.mNumberBuffers)) for buffer in buffers { let samplesCount = Int(buffer.mDataByteSize) / MemoryLayout<Int16>.size let samplesPointer = audioBufferList.mBuffers.mData!.bindMemory(to: Int16.self, capacity: samplesCount) let samples = UnsafeMutableBufferPointer<Int16>(start: samplesPointer, count: samplesCount) } guard let data = audioBufferList.mBuffers.mData else { return } /// The _Nyquist frequency_ is the highest frequency that a sampled system can properly /// reproduce and is half the sampling rate of such a system. Although  this app doesn't use /// `nyquistFrequency` you may find this code useful to add an overlay to the user interface. if nyquistFrequency == nil { let duration = Float(CMSampleBufferGetDuration(buffer).value) let timescale = Float(CMSampleBufferGetDuration(buffer).timescale) let numsamples = Float(CMSampleBufferGetNumSamples(buffer)) nyquistFrequency = 0.5 / (duration / timescale / numsamples) } if self.rawAudioData.count < AudioSpectrogram.sampleCount * 2 { let actualSampleCount = CMSampleBufferGetNumSamples(buffer) let ptr = data.bindMemory(to: Int16.self, capacity: actualSampleCount) let buf = UnsafeBufferPointer(start: ptr, count: actualSampleCount) rawAudioData.append(contentsOf: Array(buf)) } while self.rawAudioData.count >= AudioSpectrogram.sampleCount { let dataToProcess = Array(self.rawAudioData[0 ..< AudioSpectrogram.sampleCount]) self.rawAudioData.removeFirst(AudioSpectrogram.hopCount) self.processData(values: dataToProcess) } createAudioSpectrogram() } } } I am sure there are different or better ways to go about this, but the only examples I can find are on iOS and use UIKit, but I am building for MacOs. Does anyone know how display a spectrogram for an audio file without having to play the audio file? I dont mind using sox or ffmpeg if that is easier. Greatly appreciated!
Posted Last updated
.