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

Swift Documentation

Posts under Swift tag

2,226 results found
Sort by:
Post not yet marked as solved
227 Views

How can I suppress warning that "Conversion to Swift 5 is available"?

After upgrading to Xcode 13.2 I receive a warning that "Conversion to Swift 5 is available". If I click the warning then a target conversion window appears allowing me to select which targets should be migrated. My project uses a large number of Swift packages and this list contains 76 targets. 73 of these targets are from packages that target swift-tools-version: 5 or newer. The other 3 packages have swift-tools-version set to 4.x. Unfortunately these are open-source packages that I cannot change. If I try to run the migration it stops with an error that the project could not be built, with no additional information. This is incorrect as the project and all dependencies build fine. The warning is not removed if I click "Convert Later", even if "Remind Me" is unchecked. The Swift compiler version for the top-level Xcode project is set to 5. I don't understand why I'm getting this warning as it did not appear with Xcode 13.0 or 13.1. Is there a way to suppress this warning? We have a zero warning policy for our projects so I need to resolve or suppress this warning, at least for the current Xcode version (13.x).
Asked
by simonw.
Last updated
.
Post not yet marked as solved
11 Views

NSManagedObjectContext perform is only available in iOS 15 or newer

I'm working on an App that still supports iOS 13 and need to fetch some data with CoreData. This is how I would normally do it context.perform({ let results = try context.fetch(request) }) Now with Xcode 13.2 and async/await being available back to iOS 13 I get a compiler error 'perform(schedule:_:)' is only available in iOS 15.0 or newer Jumping to definition shows the following new API in CoreData @available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) extension NSManagedObjectContext { public func performAndWait<T>(_ block: () throws -> T) rethrows -> T public func perform<T>(schedule: NSManagedObjectContext.ScheduledTaskType = .immediate, _ block: @escaping () throws -> T) async rethrows -> T } When commenting out the code in the Block, it instead jumps to the old API in CoreData/NSManagedObjectContext /* asynchronously performs the block on the context's queue. Encapsulates an autorelease pool and a call to processPendingChanges */ @available(iOS 5.0, *) open func perform(_ block: @escaping () -> Void) Why does the compiler select the new variant of perform and how can I force it to use the older non-async version?
Asked
by mexx.
Last updated
.
Post not yet marked as solved
19 Views

Swift: TimelineView Updates without SwiftUI

Hi everyone. We have developed a WatchOS app in Swift for continuous heart rate monitoring. But since the introduction of Always-On-Displays we're struggling with the fact that the UI does not update while in Always-On-Standby-Mode. The documentation solution is to implement a TimelineView scheduled periodic interval: var body: some View { VStack { TimelineView(EveryMinuteTimelineSchedule()) { context in // Update UI and communicate with iPhone here but unfortunately this code is only for SwiftUI. Is there any other way or an alternative code to enable periodic UI Updates of a standby Watch display in pure Swift?
Asked
by at2 GmbH.
Last updated
.
Post not yet marked as solved
111 Views

How to start audio recording when app running on background?

I am working on audio recording. when application running on foreground i have to start audio recording and going to background at that time audio recording working fine. But my question is that how to start audio recording when i am already in background, My audio recording function fired like this: I have a Bluetooth LE device with buttons and an iOS app. Those two are paired (Bluetooth LE device and the iPhone which runs the iOS app) and the iOS app is listening for events on the Bluetooth LE device, events like a hit of a button. Now, when the user hits a button on the Bluetooth LE device, the iOS app captures the event and I am able to run code even if the app is in background, but I am not able to start a voice recording. I have already enable Background Modes: Here is my Code for Audio Recording: func startRecording() { DispatchQueue.global(qos: .background).asyncAfter(deadline: DispatchTime.now(), qos: .background) { let audioFilename = self.getDocumentsDirectory().appendingPathComponent("recording.m4a") print("record Audio \(audioFilename)") let settings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] do { self.audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings) self.audioRecorder.delegate = self self.audioRecorder.record() } catch { self.finishRecording(success: false) } } } func getDocumentsDirectory() -> URL {     let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)     return paths[0]   } I can't find proper solution to do that thing, Please suggest me proper way to do that, Thanks in Advance.
Asked Last updated
.
Post not yet marked as solved
1.4k Views

How do I pass data to another view controller in Swift 4?

Xcode, Swift 4How do I pass data to another view controller in Swift 4?Below is my code and I am getting an error message.I am getting an error on line 181. It saysCannot assign value of type 'DataToPass' to type 'ViewController'struct DataToPass { var principal: Double = 0 var balance: Double = 0 var monthlyInterest: Double = 0 var paymentNumber: Int = 0 } class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate { var valueToPass: DataToPass = DataToPass(principal: 0.00, balance: 0.00, monthlyInterest: 0.00, paymentNumber: 0) // Class-level constant to hold the months per year. let dblMONTHS_YEAR: Double = 12 // To not allow more than 1 decimal point. func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -&gt; Bool { let countdots = (textField.text?.components(separatedBy: ".").count)! - 1 if countdots &gt; 0 &amp;&amp; string == "." { return false } return true } @IBAction func textFieldCost(_ sender: TextField) { func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) { self.view.endEditing(true) } } @IBAction func textFieldDownPayment(_ sender: TextField) { func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) { self.view.endEditing(true) } } @IBAction func textFieldMonths(_ sender: TextField) { func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) { self.view.endEditing(true) } } @IBAction func textFieldAPR(_ sender: TextField) { func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) { self.view.endEditing(true) } } @IBOutlet weak var txtViewLabels: UITextView! @IBOutlet weak var txtViewResults: UITextView! // Text Field Outlets. @IBOutlet weak var txtCost: UITextField! @IBOutlet weak var txtDownPayment: UITextField! @IBOutlet weak var txtMonths: UITextField! @IBOutlet weak var txtAPR: UITextField! // Error Message. @IBOutlet weak var lblMessage: UILabel! // Buttons @IBAction func btnCalculate(_ sender: UIButton) { var dblAPR: Double = 0 // To hold the Annual Rate. var dblTotalAmount: Double = 0 // To hold the vehicle total cost. var dblCost: Double = 0 // To hold vehicle cost. var dblDownPayment: Double = 0 // To hold down payment. var intMonths: Int = 0 // To hold number of months for the loan. var dblLoan: Double = 0 // To hold the amount of the loan. var dblMonthlyPayment: Double = 0 // To hold the monthly payment. var dblTotalInterest: Double = 0 // To hold the total interest. var dblMonthlyRate: Double = 0 // To hold the monthly Rate. var monthlyInterest: Double = 0 var balance: Double = 0 var principal: Double = 0 var paymentNumber: Int = 0 var data: [String] = [] func passedValue() { func paymentStructure() { data = [] balance = dblLoan for _ in 1...intMonths { paymentNumber+=1 dblCost = Double(txtCost.text!)! dblDownPayment = Double(txtDownPayment.text!)! intMonths = Int(txtMonths.text!)! dblAPR = Double(txtAPR.text!)! monthlyInterest = balance * ((dblAPR/100)/12) principal = dblMonthlyPayment - monthlyInterest balance = balance - principal let fPrincipal = NSNumber(value: principal) let fResultPrincipal = NumberFormatter.localizedString(from: fPrincipal, number: .currency) let fBalance = NSNumber(value: balance) let fResultBalance = NumberFormatter.localizedString(from: fBalance, number: .currency) let fMonthlyInterest = NSNumber(value: monthlyInterest) let fResultMonthlyInterest = NumberFormatter.localizedString(from: fMonthlyInterest, number: .currency) data += ["\(paymentNumber). P: \(fResultPrincipal), I: \(fResultMonthlyInterest), B: \(fResultBalance)"] } valueToPass.paymentNumber = intMonths valueToPass.monthlyInterest = monthlyInterest valueToPass.principal = principal valueToPass.balance = balance } } else if txtCost.text != nil &amp;&amp; txtDownPayment.text != nil &amp;&amp; txtMonths.text != nil &amp;&amp; txtAPR.text != nil { // Clear the message. lblMessage.text = "" dblCost = Double(txtCost.text!)! dblDownPayment = Double(txtDownPayment.text!)! intMonths = Int(txtMonths.text!)! dblAPR = Double(txtAPR.text!)! // Get the APR rate. dblAPR = dblAPR / 100 // Get the monthly rate. dblMonthlyRate = dblAPR / dblMONTHS_YEAR // Get the monthly payment. dblMonthlyPayment = (dblCost - dblDownPayment) * (dblMonthlyRate / (1 - pow(1 + dblMonthlyRate, Double(-intMonths)))) // Get the amount of the loan. dblLoan = dblCost - dblDownPayment // Get the total interest. dblTotalInterest = dblMonthlyPayment * Double(intMonths) - dblLoan // Get the Total Amount. dblTotalAmount = dblCost + dblTotalInterest // Get the Vehicle Cost. dblCost = dblTotalAmount - dblTotalInterest // Format the results. let fCost = NSNumber(value: dblCost) let fResultCost = NumberFormatter.localizedString(from: fCost, number: .currency) let fDownPayment = NSNumber(value: dblDownPayment) let fResultDownPayment = NumberFormatter.localizedString(from: fDownPayment, number: .currency) let fLoan = NSNumber(value: dblLoan) let fResultLoan = NumberFormatter.localizedString(from: fLoan, number: .currency) let fMonthlyPayment = NSNumber(value: dblMonthlyPayment) let fResultMonthkyPayment = NumberFormatter.localizedString(from: fMonthlyPayment, number: .currency) let fAPR = NSNumber(value: dblAPR) let fResultAPR = NumberFormatter.localizedString(from: fAPR, number: .percent) let fTotalInterest = NSNumber(value: dblTotalInterest) let fResultTotalInterest = NumberFormatter.localizedString(from: fTotalInterest, number: .currency) let fTotalAmount = NSNumber(value: dblTotalAmount) let fResultTotalAmount = NumberFormatter.localizedString(from: fTotalAmount, number: .currency) txtViewLabels.text = " APR:\n Months: \n Cost:\n Down Payment:\n Loan Amount:\n Monthly Payment:\n Total Interest:\n Total Amo txtViewResults.text = " \(fResultAPR)\n \(intMonths)\n \(fResultCost)\n \(fResultDownPayment)\n \(fResultLoan)\n \(fResultMonthkyPayment)\n \(fResultTotalInterest)\n \(fResultTotalAmount)" passedValue() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "payout structure" { if let destVC = segue.destination as? PayoutStructure { destVC.passedData = valueToPass } } } }
Asked
by japio.
Last updated
.
Post not yet marked as solved
5.2k Views

dynamic name for variables swift

is it possible to have a dynamic variable in swift. What i want to do is have a chuck of code which writes a variable: I.Evar number = 0var person+\(number) = "on"can you help thanks
Asked
by DW_APPs.
Last updated
.
Post not yet marked as solved
67 Views

FBSSceneSnapshotRequestHandle crash

Hello, I have an App on the App Store, and today, while inspecting the App analytics on the App Store portal, I've noticed that there had been 8 crashes on the App on January 15th. I went to Firebase Crashlytics, since I used to also see the crashes on the App, and it says that there are no crashes. Then I went to Xcode to see the details of the crash, and I found this: What does this crash mean? I have no idea whatsoever. I tested the App several times, and it works perfectly. I have absolutely no idea of what this crash is. Could someone give some hints on what this crash could possibly be? Thanks.
Asked Last updated
.
Post not yet marked as solved
39 Views

Animation inside CollectionView Cell not running

I have button inside a CollectionViewCell and when tapped I want to run an animation. The animation doesn't run and I'm not sure why. Inside the Cell class @IBAction func hoursExpandBtnTapped(_ sender: Any) { UIView.animate(withDuration: 3, delay: 0, options: .curveLinear) { [self] in addressLbl.frame = CGRect(x: addressLbl.frame.minX, y: addressLbl.frame.minY, width: 20, height: addressLbl.frame.height)             } completion: { _ in             }     }
Asked Last updated
.
Post not yet marked as solved
604 Views

Swift Combine API client; return Future or AnyPublisher?

I'm implementing (for the first time) a web service client in Swift using the Combine framework. For a method that makes a single call to a web service and then closes the connection, what is considered best practice – to return a Future or a Publisher? func getSomeThing() -> Future&lt;SomeThing...&gt; { } func getSomeThing() -> AnyPublisher&lt;SomeThing...&gt; { } In Flutter, a single async value would be a "Future" and multiple async values would be a "Stream". In the WWDC 2019 talk: "Introducing Combine" Apple presents a slide that hints at Futures as the async version of a single sync value. And Publishers as the async version of sync arrays. I understand that Futures in fact are Publishers. And that there may be some subtle technical nuances to consider (greedy/lazy etc). But thinking about the communicated intent, returning a Future seems to indicate a one hit wonder pipeline better than returning an AnyPublisher. But returning a Publisher seems easier and more in line with the framework, since it's pretty easy to eraseToAnyPublisher, for example from an URLSession.DataTaskPublisher, and just return that object. Mapping a DataTaskPublisher pipeline to a Future dosen't seem to be straight forward at all. Any best practice advise would be appreciated.
Asked
by weenzeel.
Last updated
.
Post not yet marked as solved
7.9k Views

invalid mode 'kCFRunLoopCommonModes'

invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debugI get this warning when I tap either of the switches shown below. I've tried capturing the switch state in a var and using that to trigger the do/catch statement but no joy. I've even tried pulling the do/catch into separate functions and I still get the warning. Has anybody else run into this and how did you fix it?@IBAction func greetingFormat_Tapped(_ sender: UISwitch) { let theQuery = theTable_Settings.filter(settingID == 1) if sender.isOn { do { if try Database.shared.databaseConnection!.run(theQuery.update(greeting_Format &lt;- "true")) &gt; 0 { greetingFormatLabel_Outlet.text = NSLocalizedString("HelloMrSmith_String", comment: "") } else { print("greeting format true not found") } } catch { print("greeting format true update failed! Error: \(error)") } } else { do { if try Database.shared.databaseConnection!.run(theQuery.update(greeting_Format &lt;- "false")) &gt; 0 { greetingFormatLabel_Outlet.text = NSLocalizedString("HiJoe_String", comment: "") } else { print("greeting format false not found") } } catch { print("greeting format false update failed! Error: \(error)") } } }@IBAction func nonrefundableSwitch_Tapped(_ sender: UISwitch) { let theQuery = theTable_Settings.filter(settingID == 1) var itsOn: String = "" if sender.isOn { itsOn = "true" } else { itsOn = "false" } if itsOn == "true" { do { if try Database.shared.databaseConnection!.run(theQuery.update(nonRefundable_Bool &lt;- "true")) &gt; 0 { depositDueLabel_Outlet.text = NSLocalizedString("nonRefunddepositisdue_String", comment: "") } else { print("nonRefundable true not found") } } catch { print("nonRefundable true update failed! Error: \(error)") } } else { do { if try Database.shared.databaseConnection!.run(theQuery.update(nonRefundable_Bool &lt;- "false")) &gt; 0 { depositDueLabel_Outlet.text = NSLocalizedString("depositisdue_String", comment: "") } else { print("nonRefundable false not found") } } catch { print("nonRefundable false update failed! Error: \(error)") } } }
Asked Last updated
.
Post not yet marked as solved
41 Views

How to manage view when model the same but different views?

Hi, What is the best architecture/design approach for SwiftUI app where we have same data but could be slightly different or totally different views for iPhone and iPad? How to avoid code redundant? If there is some example I would really appreciate. Thanks.
Asked
by sotrosh.
Last updated
.
Post not yet marked as solved
3.5k Views

Request failed with Error Domain=NSPOSIXErrorDomain Code=28 "No space left on device"

Lately numerous network requests made from our iOS device fail with the following error: Error Domain=NSPOSIXErrorDomain Code=28 "No space left on device" UserInfo={_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask CF70E0F0-40BB-4796-B15B-3B4CCB483EE1.3, _kCFStreamErrorDomainKey=1, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask CF70E0F0-40BB-4796-B15B-3B4CCB483EE1.3" ), _kCFStreamErrorCodeKey=28} The message implies the error has to do with available disk/memory space on the device. However, after checking both there is no link to be found since there is plenty of space available. Also, the error occurs on multiple devices, all running iOS 14.4 or higher. Is there information available regarding error code 28 and what could be the culprit on iOS devices? Even better; how can this error be prevented? Thanks in advance! Kind Regards, Julian
Asked Last updated
.
Post not yet marked as solved
20 Views

WKWebView Accept Invalid (Date) SSL Certificates

I'm attempting (for a niche internal use only, it doesn't need to appear on the App Store and I'm aware there's no way this would pass their checks!) to ignore SSL certificate dates within a WKWebView I'm completely new to Swift, but not to iOS development, and this is very much a 'solve a problem quickly' rather than a properly designed app. The Info.plist has Allow Arbitrary Loads in Web Content and Allow Arbitrary Loads both set in the ATS Settings and I found this block of code here https://developer.apple.com/forums/thread/15610 func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {         guard let serverTrust = challenge.protectionSpace.serverTrust else { return completionHandler(.useCredential, nil) }         let exceptions = SecTrustCopyExceptions(serverTrust)         SecTrustSetExceptions(serverTrust, exceptions)         completionHandler(.useCredential, URLCredential(trust: serverTrust))     } Which works as expected for trusting a self-signed certificate, but if the certificate isn't yet valid or has expired it doesn't work. Is there a way to completely ignore the certificate issue and expiry date?
Asked
by rsmck.
Last updated
.
Post not yet marked as solved
185 Views

Cannot find type '<#Value: BinaryFloatingPoint#>' in scope

I tried to build your sample app Coffee Tracker WatchKit App under Xcode 13 and it failed with the message "Cannot find type '<#Value: BinaryFloatingPoint#>' in scope" on line 12 of CoffeeData. I was building the Starting Point, and the updated without modification, same result.
Asked Last updated
.
Post not yet marked as solved
21 Views

About API a USB memory accesses.

Let me question by the program code level, please. First Lightning - USB camera adapter is connected with iPhone as composition and the adapter and USB memory are connected. A character data is stocked in a USB memory, and I'd like to refer to the character data in the USB memory from application of written by oneself iOS using Swift or Objective - C. Would API which refers to the data in USB at Swift or Objective - C in the case exist? When what kind of way doing get when not existing, would I be able to refer to data in USB?
Asked
by rio5.
Last updated
.