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

Swift Documentation

Pinned Posts

Posts under Swift tag

2,084 Posts
Sort by:
Post not yet marked as solved
2 Replies
242 Views
Are there more developers noticing that metadata is not working on iOS 16 beta 1 and 2? Both possible solutions are not working: observeValue for key "timedMetadata" and AVPlayerItemMetadataOutputPushDelegate. The code I produced works fine on iOS 16 in the simulator, but not on a real device (iPhone XR).
Posted Last updated
.
Post not yet marked as solved
0 Replies
60 Views
Hi Team, We are trying to connect with our .pem file to apple, for testing pushnotification and here our UseCase Send - Connection Send -> Block a few minutes later Send -> Connection Send -> Block where Block = connection refused, so it failed to even "connect" to apple We also notice that the DNS resolved to many different IP addresses. Some work, some block some IP addresses send us reset packets which means we get connection refused and some complete the TCP handshake and work. When is the old SSL push notification supported up to before we have to swap to HTTP2? we are trying to work out IF this is still supported? any help would be appreciated Thanks in advance.
Posted
by Narijayu.
Last updated
.
Post not yet marked as solved
1 Replies
101 Views
I have a SPM framework project that includes both Swift code and JSON file resources. With a package file that looks like this: let package = Package( name: "MyTestData", products: [ .library( name: "MyTestData", targets: [ "MyTestData", ] ), ], targets: [ .target( name: "MyTestData", dependencies: [], path: "Sources", sources: ["ios"], resources: [ .copy("payloads"), .copy("snippets"), ] ), ] ) Now all the SPM packages resolve correctly and the code compiles and works, yet the Xcode workspace is showing errors like this: Now payloads and snippets are not projects and I've tried all sorts of variations of path, sources, exclude, resource in my Package file and either I get the errors and everything works, or the errors disappear and the project doesn't work. I don't know what the issue is and there's nothing in the resolving or build logs. Does anyone know what might be the problem here?
Posted
by drekka.
Last updated
.
Post marked as solved
4 Replies
63 Views
Am trying to port away from .textLabel.text, as per Apple but I can't seem to find the way to get the text I set. I now set my cells this way: let cell = UITableViewCell() var config = cell.defaultContentConfiguration() config.text = dbClass.nameList[indexPath.row].clientName config.textProperties.color = .black config.textProperties.alignment = .center cell.contentConfiguration = config But when I try to get the text of a selected cell (once the user hits the OK button) I can't seem to reverse engineer how to get the text. let cell = myClientList.cellForRow(at: myInvsList.indexPathForSelectedRow!) let config = cell?.contentConfiguration dbClass.curMasterinvList = ?????? (can't find what property to read here I even tried let config = cell?.defaultContentConfiguration() Hoping that the text would be in there, but the text there is blank, so am assuming that's just the standard config before I've changed it. I have Googled as much as possible, but can't seem to find this very simple need.
Posted
by SergioDCQ.
Last updated
.
Post not yet marked as solved
0 Replies
45 Views
Swift Package Manager synthesises a module accessor for bundle resources (as described in WWDC 2020 Session 10169 Swift packages: Resources and localisation and SE-0271 > Runtime Access to Resources Bundle. This is great, but I'd like to supply a different implementation of module. When I try to extend Bundle with my own module accessor the compiler complains that there are two module implementations. Is it possible to disable the SPM resource_bundle_accessor synthesis behaviour?
Posted Last updated
.
Post marked as solved
4 Replies
98 Views
I'm using Xcode 13.4.1 and targeting iOS 15.0. I have aSwiftUI app that crashes as soon as you click a button that changes a variable from true to false: Button("Close Side by Side Mode") { mainScreenRecs.isViewingSideBySide = false } This is the only place where the variable is changed; everything else is just SwiftUI reading the variable to determine whether to show views or not, like this: var body: some View {         VStack(spacing: 0) {                 HStack {                     if mainScreenRecs.isViewingSideBySide {                         Text(catalogModel.title)                     } When I look at the debug stack, I can see that the previous modification says LayoutComputer.EngineDelegate.childGeometries(at:origin:), which makes me wonder if it's related to SwiftUI: I see this in the debug output, which has the additional note about AttributeGraph: cycle detected through attribute, another possible SwiftUI problem: I tried wrapping this code in DispatchQuery.main.async, like this: Button("Close Side by Side Mode") { DispatchQueue.main.async { mainScreenRecs.isViewingSideBySide = false } } but it didn't help. Is it possible this is a SwiftUI bug? I hate to think that because it leaves me stuck without a solution, but I can't figure out what else I could check or try.
Posted Last updated
.
Post not yet marked as solved
0 Replies
49 Views
I am working on a test app utilizing UISplitViewController. I search for ContainerView and drag it onto the Detail View. Then I search for an ImageView and drag it onto the Detail View. The ContainerView disappears and is replaced by the ImageView. I've deleted and recreated several times, and have also rebooted and it doesn't change how it works. Have you experienced this or is there a fix? I am using Xcode 13.4, and Monterey 12.4.
Posted
by jamdia.
Last updated
.
Post not yet marked as solved
0 Replies
76 Views
I have an IOS application who uses coredata As I want to develop and App extension which needs to share coredata with my app(Yes, I made a group App), I thought a good solution would be to create a framework with the, coredata model. I did it, but after that the coredata of the main app is no longer necessary. and I think I made a mistake when removing the file xcdatamodel from my app. when I refer to an entity in the main application, it doesn't use the entity of the framework. when I right click on an entity instance in my main application, I see a file which is: entity+CoreDataClass and of course I don't find it in the finder. Did I made a mistake by simply remove the xcdatamodel from my App? Do I have something to clean?
Posted Last updated
.
Post not yet marked as solved
1 Replies
90 Views
I'm not sure I'm even using the right terminology to describe the question, but I'll try to explain. I have a macOS utility application (LSUIElement=true) that does various things, some on a repeated schedule in the background. If there are multiple accounts on the computer, and "Fast User Switching" is enabled, then my application runs these background tasks for multiple users at a time -- fast switching to another user doesn't stop the application from doing things on a timer in the background (which I guess makes sense). One of the background repeating tasks is expensive and makes no sense to do if the user isn't the "current" or "foreground", or "active" (terminology?) user. So I found myself wanting to ask the question programatically "does my user have the screen?" I've done a lot of googling and exploring partially undocumented Swift and Objective-C APIs trying to figure this out, and I'm not sure if I'm on the right track, but was hoping someone could correct me or point me to some better concepts/resources/APIs, if possible. The best I've been able to come up with is querying who the "Console User" is -- which seems almost always to map to the user "with the screen". But I honestly don't even know what the Console User really indicates, and if it's an accurate proxy for the question I'm trying to ask, or if it's some vestigial unix red-herring. Here's some working Swift code that sort-of seems to answer the question I'm asking: import Foundation import SystemConfiguration func currentUserHasScreen() -> Bool { var uid: uid_t = 0 SCDynamicStoreCopyConsoleUser(nil, &uid, nil) return uid == getuid() } All that said, I'm hoping someone could share their knowledge on some specific questions related to this issue: What exactly is the ConsoleUser, and what information is it meant to convey? Does the Swift function shown above seem like an appropriate/correct/safe way to figure out if the current user has the screen? Is it even correct to ask "who has the screen?" -- could multiple users have the screen? (I experimented and was able to be logged in normally with one user on a machine, and then I screen-shared a different user, both worked at the same time -- who "has the screen" in that scenario?) Would it be better or more correct to ask "does this user have ANY screen/display?" For my use case, the background task has to do with taking screenshots, I don't want to take screenshots if nobody is logged in or looking at a screen (even though the OS happily will do so). When running the experiment mentioned in number 3 above, the screen sharing app prompted me saying "harriet" is currently using the display on "mini" -- what core concepts are being leveraged here? -- how does the OS know who "has the display", and is that what I should be querying instead? Would greatly appreciate any insight on as many of these issues as anyone has knowledge of, and I think future googlers would as well. 🙏
Posted
by jaredh159.
Last updated
.
Post not yet marked as solved
0 Replies
74 Views
I have an App that connects to an IOT device via Bluetooth. I gave it the proper permissions in the info.plist file, and it works fine when I run it from XCode, is able to connect to and communicate with the IOT device via bluetooth. However, when I installed the App on another device via TestFlight, it does not work despite having all the same permissions and the exact same code. I do not know how to debug it since in Dev it works fine. Does anyone have any idea how I can track down what is happening?
Posted Last updated
.
Post not yet marked as solved
0 Replies
54 Views
My app used to rely on standard iOS Numpad Keyboard as a textField.inputView. The textField could group typed numbers (1000 -> 1 000, 50067 -> 50 067 etc) and limit the amount of numbers after the decimal point as 2 max: https://i.stack.imgur.com/69LVr.gif (GIF) I've created a custom numpad keyboard view and implement its logic with UITextInput protocol according to that guide on StackOverflow. I can't understand of how to deal with the code I used for grouping and limit numbers with standard iOS Numpad. Because it doesn't work properly after I type numbers from my new custom Numpad (only 2 numbers): https://i.stack.imgur.com/f3u3n.gif (GIF) The code I use for grouping and limit numbers after decimal point in a textField: func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.groupingSeparator = " " formatter.maximumFractionDigits = 2 let textString = textField.text ?? "" guard let range = Range(range, in: string) else { return false } let updatedString = textString.replacingCharacters(in: range, with: string) let correctDecimalString = updatedString.replacingOccurrences(of: ",", with: ".") let completeString = correctDecimalString.replacingOccurrences(of: formatter.groupingSeparator, with: "") guard completeString.count <= 12 else { return false } guard !completeString.isEmpty else { return true } textField.text = completeString return string == formatter.decimalSeparator } Custom NumpadView: class NumpadView: UIView { var target: UITextInput? init(target: UITextInput) { super.init(frame: .zero) self.target = target initializeSubview() } required init?(coder: NSCoder) { super.init(coder: coder) initializeSubview() } func initializeSubview() { let xibFileName = "NumpadView" let view = Bundle.main.loadNibNamed(xibFileName, owner: self, options: nil)![0] as! UIView self.addSubview(view) view.frame = self.bounds self.autoresizingMask = [.flexibleWidth, .flexibleHeight] } @IBAction func buttonPressed(_ sender: NumpadButton) { insertText((sender.titleLabel!.text)!) } func insertText(_ string: String) { guard let range = target?.selectedRange else { return } if let textField = target as? UITextField, textField.delegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) == false { return } target?.insertText(string) } } extension UITextInput { var selectedRange: NSRange? { guard let selectedRange = selectedTextRange else { return nil } let location = offset(from: beginningOfDocument, to: selectedRange.start) let length = offset(from: selectedRange.start, to: selectedRange.end) return NSRange(location: location, length: length) } } 2.How I initialize it in a VC: override func viewDidLoad() { super.viewDidLoad() textField.delegate = self textField.inputView = NumpadView(target: textField) } Test project on GitHub: CLICK What should I do so the code in shouldChangeCharactersIn method work for my custom Numpad?
Posted Last updated
.
Post not yet marked as solved
3 Replies
131 Views
Hi all, I have been facing a problem while loading a file from the firebase storage. Basically in my code i have a data model which is the file/document (pdf in this case), a manager which goes into the database of Firebase to fetch the object and finally two views, one to list the files fetched and another one to show the document. I can fetch all the documents with their specific data, pass them to my view and then show the document pdf in another view. Everything seems correct but the problem comes when opening one of this docs. First, the doc doesn't open at first so you need to close the view and try to open the doc again. Then when i want to open another doc from my list, when i click on it the previous document is shown and not the correct one, so i need to do the same, close the view and click again on the doc to open the correct one. So at the end what i'm looking for is to open the doc just clicking once but i don't know where is my problem. List of docs: 1st time: 2nd time: 2nd doc but 1st time: 2nd doc and 2nd time clicking on it: Here is my code Model: struct DocumentoPdf {     let titulo: String     let docUrl: URL?     let id: String     let storageUrl: String } Manager which fetches the documents from firebase: final class DatabaseManager { [...]     public func getNovedades(completion: @escaping ([DocumentoPdf]) -> Void) {         database.collection("novedades").getDocuments { snapshot, error in             guard let documents = snapshot?.documents.compactMap ({ $0.data() }), error == nil else {                 return             }             let novedades: [DocumentoPdf] = documents.compactMap({ dictionary in                 guard let id = dictionary["id"] as? String,                       let titulo = dictionary["titulo"] as? String,                       let docUrlString = dictionary["docUrl"] as? String,                       let storageUrl = dictionary["storageUrl"] as? String else {                           return nil                       }                 let novedad = DocumentoPdf(titulo: titulo,                                            docUrl: URL(string: docUrlString),                                            id: id,                                            storageUrl: storageUrl)                 return novedad             })             completion(novedades)         }     } } First View: class NovedadesViewControllerViewModel {     let docUrl: URL?     var docData: Data?     init(docUrl: URL?) {         self.docUrl = docUrl     } } class NovedadesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, PDFViewDelegate {     private var tableView =  UITableView()    private var doc = PDFDocument()     public func configureDocPdf(with viewModel: NovedadesViewControllerViewModel) {         if let data = viewModel.docData {             doc = PDFDocument(data: data)!         }         else if let url = viewModel.docUrl {             // fetch doc & cache             let task = URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in                 guard let data = data else {                     return                 }                 viewModel.docData = data                 DispatchQueue.main.async {                     self?.doc = PDFDocument(data: data)!                 }             }             task.resume()         }     }     private var novedades: [DocumentoPdf] = []     private func obtenerNovedades() {         DatabaseManager.shared.getNovedades() { [weak self] novedades in             self?.novedades = novedades             DispatchQueue.main.async {                 self?.tableView.reloadData()             }         }     }     override func viewDidLoad() { [...]         obtenerNovedades() [...]     } [... sections, rows in section...]     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {         let novedad = novedades[indexPath.row]         let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)         cell.textLabel?.text = novedad.titulo         return cell     }     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {         let novedad = novedades[indexPath.row]         switch indexPath.section {         case 0:             configureDocPdf(with: .init(docUrl: novedad.docUrl))             let lectorPdfView = LectorPdfViewController(doc: self.doc, nameDoc: novedad.titulo)             self.present(lectorPdfView, animated: true, completion: nil)         default:             break         }     } } Second View to load the pdf: class LectorPdfViewController: UIViewController, PDFViewDelegate {     private let navBar = UINavigationBar()     private let pdf = PDFView()     let nameDoc: String     let doc: PDFDocument     init(doc: PDFDocument, nameDoc: String) {         self.doc = doc         self.nameDoc = nameDoc         super.init(nibName: nil, bundle: nil)     }     required init?(coder: NSCoder) {         fatalError()     }     override func viewDidLoad() {         super.viewDidLoad()         view.backgroundColor = .systemBackground         view.addSubview(navBar)         view.addSubview(pdf)         pdf.document = self.doc         pdf.delegate = self         let item = UINavigationItem(title: self.nameDoc)         navBar.setItems([item], animated: false)         navBar.barTintColor = .systemBackground     }     override func viewDidLayoutSubviews() {         navBar.frame = CGRect(x: 0,                               y: 0,                               width: view.frame.size.width,                               height: 50)         pdf.frame = CGRect(x: 0,                            y: navBar.frame.height,                            width: view.frame.size.width,                            height: view.frame.size.height - navBar.frame.height)     } } Please if someone can help me with this will be fantastic. I hope you understood my code and my problem. Sorry for my bad english Thank you so much in advance
Posted
by moraKevin.
Last updated
.
Post not yet marked as solved
3 Replies
183 Views
How can we assign the unique accessibility identifiers to the urls in UITextView In the accessibility inspector, I am able to see the urls as separate elements but not able to set the accessibility identifiers for them. The accessibility identifiers are needed for automation testing. In the screenshots added here, i have taken a UITextView which has urls in it.
Posted Last updated
.
Post not yet marked as solved
0 Replies
56 Views
Hello, I want to add a .mlmodel to my swift package to have a test to verify that the compilation is working. targets: [     .target(       name: "packageName",       dependencies: ["package1"]     ),     .testTarget(       name: "packageNameTests",       dependencies: ["packageName"],       resources: [         .copy("Resources/testmodel.mlmodel"),       ]     )   ] My problem is the .mlmodel is always as a compiled model after bundling let docsPath = Bundle.module.resourcePath! let docsArray = try fileManager.contentsOfDirectory(atPath: docsPath)     print(docsArray) leads to ["testmodel.mlmodelc"] I am excepting testmodel.mlmodel to be present instead. I find it strange that copy is processing the ressource. Is there a workaround ? I am using Xcode 14 beta but there is a similar post on StackOverflow without answer regarding this issue https://stackoverflow.com/questions/64298356/how-to-add-uncompiled-mlmodel-to-xcode-unittests-bundle that got this problem with Xcode 12 Thank you
Posted
by AymericF.
Last updated
.
Post marked as solved
4 Replies
1.6k Views
I try to exclude some activities from UIActivity. It works as expected when exclusion is done directly with the activity, as with: UIActivity.ActivityType.message, UIActivity.ActivityType.airDrop but not when activity is declared with an init as with: UIActivity.ActivityType(rawValue: "net.whatsapp.WhatsApp.ShareExtension"), UIActivity.ActivityType(rawValue: "com.ifttt.ifttt.share"), So, with the following code: let excludedActivityTypes = [ UIActivity.ActivityType.message, UIActivity.ActivityType.airDrop, UIActivity.ActivityType(rawValue: "net.whatsapp.WhatsApp.ShareExtension"), UIActivity.ActivityType(rawValue: "com.ifttt.ifttt.share") ]         let activityVC = UIActivityViewController(activityItems: [modifiedPdfURL], applicationActivities: nil)          activityVC.excludedActivityTypes = excludedActivityTypes message and airDrop do not show, but WhatsApp and IFTTT still show. I have tested with         activityVC.completionWithItemsHandler = { (activity, success, modifiedItems, error) in             print("activity: \(activity), success: \(success), items: \(modifiedItems), error: \(error)")         } that WhatsApp and IFTTT services are effectively the ones listed here. When selecting WhatsApp, print above gives: activity: Optional(__C.UIActivityType(_rawValue: net.whatsapp.WhatsApp.ShareExtension)), success: false, items: nil, error: nil
Posted
by Claude31.
Last updated
.
Post not yet marked as solved
7 Replies
99 Views
Hi! My app is showing a rare crashes that I am not able to reproduce. The stack trace starts with lines like the following: 0 MyApp 0x00000001028edf38 function signature specialization <Arg[0] = Dead> of MyApp.CollectionViewDataSource.collectionView(_: __C.UICollectionView, didSelectItemAt: Foundation.IndexPath) -> () (<compiler-generated>:0) 1 MyApp 0x00000001028ed258 @objc MyApp.CollectionViewDataSource.collectionView(_: __C.UICollectionView, didSelectItemAt: Foundation.IndexPath) -> () (<compiler-generated>:0) 2 UIKitCore 0x00000001a4fd806c -[UICollectionView _selectItemAtIndexPath:animated:scrollPosition:notifyDelegate:deselectPrevious:performCustomSelectionAction:] + 1020 3 UIKitCore 0x00000001a536effc -[UICollectionView touchesEnded:withEvent:] + 612 … What does Arg[0] = Dead actually mean and what could I do to avoid this crash?
Posted Last updated
.
Post not yet marked as solved
5 Replies
1.2k Views
For context: I'm working on a score pad app, with the ability to have a column of PKCanvases, so you can just hand write things without them being scribbled into text. As part of my stress testing, I basically filled the grid with ~50 canvases, and it seems that after a certain amount of CanvasViews are added to the score pad, my M1 iPad Pro GPU is unable to keep up. Occasionally, a cell will just entirely render as magenta, and I will have dozens and dozens of Execution of the command buffer was aborted due to an error during execution. Insufficient Memory (IOAF code 8) logs thrown to the console. I honestly don't know where to go from here. I recognize that what I'm doing is almost definitely not what PencilKit was designed for, but I also know the API is relatively young. I can't tell if this is a bug that should be fixed by Apple, or entirely my fault and a sign that I need to redo the entire thing. I've attached a screenshot with the magenta cell, there's also another two cells where the pencil strokes are just thick black squares. I'd appreciate any advice or help, I can't even seem to find any way to detect and recover from this in my code, as trying to search for Metal errors gives me discussions about writing Metal apps, which this isn't. It's a pure SwiftUI app with some PencilKit canvases.
Posted
by pgelvinaz.
Last updated
.
Post not yet marked as solved
1 Replies
90 Views
Hi, I can't seem to find any examples for the content processed completion handler connection.send(content: data , contentContext: context, completion: NWConnection.SendCompletion.contentProcessed(({ (error) in   if let err = error {           print("\(err)")         } else {           print("Sent successfully")         }  }))) I think its used to implement send side flow control, but I want to know if anyone has any good examples of it being applied that would help me understand it better. If I'm sending a constant stream of data how can I use this completion handler to respect the back-pressure from the connection
Posted
by willeum43.
Last updated
.
Post marked as solved
5 Replies
2.1k Views
I'm trying to remove all the whitespaces from the NSNumberFormatter string. It seems it adds Unicode 160 as a whitespace instead of Unicode 32 and then String's stringByReplacingOccurrencesOfString doesn't work. Is this correct behavior and how should I remove the whitespaces?let formatter = NSNumberFormatter() formatter.locale = NSLocale(localeIdentifier: "fi") formatter.numberStyle = .CurrencyStyle formatter.currencyCode = "EUR" formatter.currencySymbol = "" let value = formatter.stringFromNumber(1234) ?? "" //"1 234,00 " let trimmed = value.stringByReplacingOccurrencesOfString(" ", withString: "") // "1 234,00 " let chars = value.utf16.map { $0 } chars // [49, 160, 50, 51, 52, 44, 48, 48, 160]
Posted
by jsslai.
Last updated
.