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

Swift Documentation

Pinned Posts

Posts under Swift tag

2,401 Posts
Sort by:
Post not yet marked as solved
0 Replies
16 Views
Hi. this is my observable object final class ToolbarItemProperties: ObservableObject {   var visible = false   var disabled = false   var icon = "questionmark"   var action: () -> Void = { }   var opacity: Double = 1 } the opacity property value should either be 0.5 or 1 depending on the value of the property disabled. How to listen to it? The purpose for this is because if i set a button to disabled, it does not render any way to the user to let them know it is disabled. So i thought of changing the opacity instead, hence the opacity property. So if i do something like this item.disabled = true the opacity property value should become 0.5. if disabled is set to false, the opacity value will be 1.
Posted
by chitgoks.
Last updated
.
Post not yet marked as solved
8 Replies
108 Views
Hello! I will show what is going on here with a very simple example: var str: String str = "Test" func test(param: String) { print(param) } What is happening is: running this in my computer it shows: Test running in another Mac it shows: Optional("Test") This is a simple code, but because of that "optional" the real code will give an error because of "Invalid character" I tried wrap with String() String(describing: ) and I can't fix that. Any help on this? Thanks
Posted Last updated
.
Post not yet marked as solved
0 Replies
21 Views
An API changed its JSON, a field named contactMedium, that was coming in form of a Array changed to an Object: was like this : { "contactMedium": [         {             "type": "EMAIL",             "characteristic": {                 "emailAddress": "ibenedit"             }         }     ], } become like this : { "contactMedium": {         "characteristics": {             "emailAddress": "ibeneditobr"         },         "type": "EMAIL"     }, } My question is, how I implement the init's struct ("init(from decoder: Decoder) throws {") , to convert from object to Array ? In my struct I tried to change: from : public var contactMedium: [ContactMedium]? to : public var contactMedium: ContactMedium? But app crashes in various places, because of use the array's methods like filter.
Posted
by aramiku.
Last updated
.
Post not yet marked as solved
0 Replies
16 Views
I'm trying to create a new instance of my class "people" and add it to my list called listOfPeople. At the start, I ask how many people am I going to add. After I answer that, I add 1 to the variable "level" so I can continue as if it where a for loop. Now at level 1, I add the name and numberAssigned to the new instance which would supposedly go in listOfPeople in the position in which the variable counter is on. After I click the button with text "Add name" I would add another name and so on until I reach the numberOfpeople, so again, trying to simulate a for loop (I'm aware I have not added the logic for the textfield and button to add a new instance and stop when counter reaches the numberOfpeople). However, in this case, after I add the persons name and numberAssigned, it gives me the error in image number three. Which says "Thread 1: Fatal error: Index out of range." How could I make this work? I learned how to do this in c++ but I clearly do not know how to accomplish it in swiftui. Any help is appreciated! ;) I could make it work this way, the only problem is that if the user wants to add 1,000 people, I would have to have 1,000 variables pre-created, which I do not want, I want to be able to do it as a for-loop per se.
Posted Last updated
.
Post not yet marked as solved
1 Replies
32 Views
Hi, I'm trying to create our app splash screen which I need a video to play in the background. I've currently got the video into my project under the following code with AV kit/foundation imported:     VideoPlayer(player: AVPlayer(url: Bundle.main.url(forResource: "XXXXXX", withExtension: "mp4")!))       .frame(height: 400)       But I need to complete three tasks: Make the video full screen Remove the player buttons Play the video automatically All resources online seem outdated and don't work on Xcode 14. Any help from a pro would be greatly appreciated! Thanks
Posted
by Normo.
Last updated
.
Post marked as solved
7 Replies
56 Views
Hello, I use a timer shared on GitHub. I want to display the last LAP recorded under the stopwatch (see screenshot). I manage to recover the LAP but not the LapTime. Thank you in advance for your assistance. struct ContentView: View {     let timer = Timer.publish(every: 0.01, on: .main, in: .common).autoconnect()          @State var minutes  = 0     @State var seconds = 0     @State var centiseconds = 0     @State var running = false     @State var lapTimes : [LapTime] = []     @State var lapCount = 1     @State var lapMinutes = 0     @State var lapSeconds = 0     @State var lapCentiseconds = 0          var body: some View {         VStack{             Text(getTimeString(cS: self.lapCentiseconds, sS: self.lapSeconds, mS: self.lapMinutes))                 .font(.system(size: 60, design: .monospaced))                 .frame(width: 300.0, height: 100.0)                 .onReceive(timer){_ in                     if(self.running){                         self.timerCalcs()                     }             }             Text(getTimeString(cS: self.centiseconds, sS: self.seconds, mS: self.minutes))                 .font(.system(size: 60, design: .monospaced))                 .frame(width: 300.0, height: 100.0)                 .onReceive(timer){_ in                     if(self.running){                         self.timerCalcs()                     }             }             Text("Lap \(lapCount - 1)") //            Text(time)                                       HStack{                 Button(action: {                     if(!self.running){                         self.minutes = 0                         self.seconds = 0                         self.centiseconds = 0                         self.lapTimes = []                         self.lapMinutes = 0                         self.lapSeconds = 0                         self.lapCentiseconds = 0                         self.lapCount = 1                     }                     else{                                                  self.lapTimes.append(LapTime(n: self.lapCount, t: self.getTimeString(cS: self.lapCentiseconds, sS: self.lapSeconds, mS: self.lapMinutes)))                         self.lapCount += 1                         self.lapMinutes = 0                         self.lapSeconds = 0                         self.lapCentiseconds = 0                     }                 }) {                     ZStack{                         Circle().fill(Color.gray).frame(width: 100, height: 100)                         self.running ? Text("Lap").foregroundColor(Color.white).font(.system(size: 20, design: .monospaced)) : Text("Reset").foregroundColor(Color.white).font(.system(size: 20, design: .monospaced))                     }                 }                                  Spacer()                 Button(action: {                     self.running = !self.running                 }) {                     ZStack{                         Circle().fill(self.running ? Color.red : Color.green).frame(width: 100, height: 100).font(.system(size: 20, design: .monospaced))                         self.running ? Text("Stop").foregroundColor(Color.white).font(.system(size: 20, design: .monospaced)) : Text("Start").foregroundColor(Color.white).font(.system(size: 20, design: .monospaced))                     }                 }             }.padding()             List{                 LapTime(n: self.lapCount, t: self.getTimeString(cS: self.lapCentiseconds, sS: self.lapSeconds, mS: self.lapMinutes))                 ForEach(self.lapTimes.reversed()) { time in                     time                 }             }         }              }          func timerCalcs(){         if(self.centiseconds < 99){             self.centiseconds += 1         }         else{             self.centiseconds = 0             if(self.seconds < 59){                 self.seconds += 1             }             else{                 self.seconds = 0                 self.minutes += 1             }         }                  if(self.lapCentiseconds < 99){             self.lapCentiseconds += 1         }         else{             self.lapCentiseconds = 0             if(self.lapSeconds < 59){                 self.lapSeconds += 1             }             else{                 self.lapSeconds = 0                 self.lapMinutes += 1             }         }     }          func getTimeString(cS: Int, sS : Int, mS: Int) -> String{         var centiString = String(cS)         var secString = String(sS)         var minString = String(mS)         if(cS<10){             centiString = "0\(cS)"         }         if(sS<10){             secString = "0\(sS)"         }         if(mS<10){             minString = "0\(mS)"         }         return "\(minString):\(secString).\(centiString)"     } } struct LapTime : View, Identifiable{     let id = UUID()     let num : Int     let time : String          var body : some View{         HStack{             Text("Lap \(num)").font(.system(size: 20, design: .monospaced))             Spacer()             Text(time).font(.system(size: 20, design: .monospaced))         }     }          init(n : Int, t : String){         num = n         time = t     } }
Posted
by Hypo78.
Last updated
.
Post not yet marked as solved
3 Replies
66 Views
How i can open Location services direct to my app? I want it to go to the screen where the user chooses allow location or not can be enabled in the app.. UIApplication.shared.open(URL(string: "App-prefs:LOCATION_SERVICES")!) this code open for me only the location services but how i can open location setting to my app?
Posted
by ODev.
Last updated
.
Post not yet marked as solved
1 Replies
46 Views
Hi, There seems to be a performance issue or bug with NavigationLinks in a List, whenever the user scrolls "fast" over multiple rows over. Without a NavigationLink, the below example prints the indices in the console in right order, however, with a NavigationLink, the indices are not updated correctly, and e.g. fast scrolling from row 20 to 70 doesn't update any value. More specifically, this is an issue with List rows using AsyncImage with placeholders, where the list doesn't update the specified row, and therefore still shows the placeholder image. To then update the image, the user has to interact anywhere on the screen. I am using the newest XCode version and am using iOS 16. I can replicate it in the Simulator as well as on my iPhone. NavigationStack {             List(0...100, id: \.self) { index in                 NavigationLink(value: index) {                     Text(index.description)                         .onAppear {                             let _ = print(index, " appearing")                         }                         .onDisappear {                             let _ = print(index, " disappearing")                         }                 }             }         }
Posted
by Dastan.
Last updated
.
Post marked as solved
1 Replies
32 Views
Hi. I am using Kingfisher library to load images. My problem is that when i resize the width, the calculated height does not follow. the height of the image when displayed is still short. What could possibly be wrong in my code? import SwiftUI import Kingfisher struct MyView: View {       var geometryProxy: GeometryProxy       var body: some View {     HStack {       HStack {         KFImage.url(URL(string: "https://volcano.si.edu/gallery/photos/GVP-11076.jpg"))           .cancelOnDisappear(true)           .fade(duration: 0.25)           .resizable()           .scaledToFit()       }       .frame(maxWidth: geometryProxy.size.width * 0.4, maxHeight: getHeight(Float(geometryProxy.size.width) * 0.4, Float(geometryProxy.size.height), Float(geometryProxy.size.width)))       Text("Text 1 Label")         .frame(maxWidth: geometryProxy.size.width * 0.65, alignment: .topLeading)         .padding(.leading, 10)         .padding(.top, 3)       Image(systemName: "chevron.right")         .frame(maxWidth: geometryProxy.size.width * 0.05)         .padding(.leading, 0)     }     .contentShape(Rectangle())   }       private func getHeight(_ imageWidth: Float, _ imageHeight: Float, _ screenWidth: Float) -> CGFloat { //    let ratio = Float(placeholder!.size.height / placeholder!.size.width) //    print(ratio) //    print(ratio * width) //    print("______") //    return CGFloat(ratio * width)     let ratio = screenWidth / imageWidth     return CGFloat(imageHeight * ratio)   } } The Image should expand since i set the width of the image to at least 40% of the screen width. Or could my calculation for getting the height may be wrong? Thougts?
Posted
by chitgoks.
Last updated
.
Post marked as solved
2 Replies
240 Views
Hi everyone. For example, i want to develop attendance check application. User will come to classroom, then they will use fingerprint reader and my app will check on databases that any match on. (I will register before) Can i use my fingerprint reader for my application? In macos or ios? platform dosen't matter. Thanks in advance.
Posted
by GospaX.
Last updated
.
Post not yet marked as solved
4 Replies
80 Views
I develop an App which has a quicklook preview for files located on a web server To realize this preview, I download the file and access it with a QLPreviewController When I use simulator, I can see the downloaded files somewhere in library/developper/coresimulator..... and so on of my mac, and I can manually delete them. But if I search these files on the IPhone simulator, I can't find them. What when I run the application on my real device? How will I be able to delete these files? because I think it take place in the IPhone
Posted Last updated
.
Post not yet marked as solved
6 Replies
2.7k Views
My debug compile is failing with: Illegal instruction: 4I can archive and release to testflight with no problem.. the program happens when running in debugger what is up with this?
Posted
by nf_ramsey.
Last updated
.
Post not yet marked as solved
55 Replies
24k 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 not yet marked as solved
0 Replies
42 Views
Hello, Ive ben having an issue with one of my Apps since Ventura came out. The app won't create a new contact It fails giving a few different warnings but no real error. I have tried it unto Ventura 13.0.1 (22A400) The error is 2022-12-03 09:33:54.543143+1000 **** [1941:15105] [api] Attempt to write notes by an unentitled app 2022-12-03 09:33:54.580714+1000 **** [1941:15105] [plugin] CDX_AB_GetGroupCollectionPath: nil group 2022-12-03 09:33:54.580765+1000  **** [1941:15105] [plugin] CDX_AB_GetGroupCollectionPath: nil group 2022-12-03 09:33:54.581969+1000 **** [1941:15105] [ABCDContact] An ABCDRecord is being saved without having a container assignment. Assigning the contact to <CNCDContainer 0x6000013c92c0 ab>. Please remember to assign contacts to containers to avoid recurring container lookup and contact re-validation costs. . When I follow the instructions on this page https://developer.apple.com/documentation/contacts to create a new contact It fails on Ventura to create a new contact and I don't know why. So I submitted a feedback Assistant request (FB11721907) But I also went ahead and got Notes field access as that was one of the warnings. That got approved, Now I would like help adding it in my project. I logged into the Developer Portal and in Identifiers, located my app and went to Additional Capabilities ticked the Box marked Contacts Notes Field Access. Then instructions in the email say 'Once you’ve finished generating the profile, you can use it in Xcode like any other manually-generated profile.' Im not sure what this means. I tried to add 'com.apple.developer.contacts.notes' Boolean, YES, to the entitlement file as described in https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_developer_contacts_notes but the app doesn't launch when it's added. And if I put it into the info.plist file it does nothing. Also im not sure how to add the purpose string.
Posted Last updated
.
Post not yet marked as solved
2 Replies
551 Views
Apple Documentation says that there is only one CNContainer in an iOS device of type local. Creating a container of type exchange requires using Exchange, and creating a container of type cardDAV requires a server also. Is there any way to create a container of type unassigned? I would need to do this programmatically in Swift to use in my iOS app. This question and the posts it mentions give no answer.
Posted Last updated
.
Post not yet marked as solved
0 Replies
54 Views
Updated info below Full disclosure: I do have this question over on StackOverflow, but I am at a standstill till I find a way to move forward, debug, etc. I am trying to recognize prerecorded speech in Swift. Essentially it either detects no speech, detects blank speech, or works on the one prerecorded file where I screamed a few words. I can't tell where the headache lies and can't figure out if there's a more detailed way to debug this. I can't find any properties that give more detailed info. Someone on SO did recommend I go through Apple's demo, here. This works just fine, and my code is very similar to it. Yet the main difference remains if there is something about the way I save my audio files or something else is leading to my headaches. If anyone has any insight into this I would very much appreciate any hints. My question over on StackOverflow Updated info below, and new code Updated info It appears that I was calling SFSpeechURLRecognitionRequest too often, and before I completed the first request. Perhaps I need to create a new instance of SFSpeechRecognizer? Unsure. Regardless, I quickly/sloppily adjusted the code to only run it once the previous instance returned its results. The results were much better, except one audio file still came up as no results. Not an error, just no text. This file is the same as the previous file, in that I took an audio recording and split it in two. So the formats and volumes are the same. So I still need a better way to debug this, to find out what it going wrong with that file. The code where I grab the file and attempt to read it func findAudioFiles(){ let fm = FileManager.default var aFiles : URL print ("\(urlPath)") do { let items = try fm.contentsOfDirectory(atPath: documentsPath) let filteredInterestArray1 = items.filter({$0.hasSuffix(".m4a")}) let filteredInterestArray2 = filteredInterestArray1.filter({$0.contains("SS-X-")}) let sortedItems = filteredInterestArray2.sorted() for item in sortedItems { audioFiles.append(item) } NotificationCenter.default.post(name: Notification.Name("goAndRead"), object: nil, userInfo: myDic) } catch { print ("\(error)") } } @objc func goAndRead(){ audioIndex += 1 if audioIndex != audioFiles.count { let fileURL = NSURL.fileURL(withPath: documentsPath + "/" + audioFiles[audioIndex], isDirectory: false) transcribeAudio(url: fileURL, item: audioFiles[audioIndex]) } } func requestTranscribePermissions() { SFSpeechRecognizer.requestAuthorization { [unowned self] authStatus in DispatchQueue.main.async { if authStatus == .authorized { print("Good to go!") } else { print("Transcription permission was declined.") } } } } func transcribeAudio(url: URL, item: String) { guard let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US")) else {return} let request = SFSpeechURLRecognitionRequest(url: url) if !recognizer.supportsOnDeviceRecognition { print ("offline not available") ; return } if !recognizer.isAvailable { print ("not available") ; return } request.requiresOnDeviceRecognition = true request.shouldReportPartialResults = true recognizer.recognitionTask(with: request) {(result, error) in guard let result = result else { print("\(item) : There was an error: \(error.debugDescription)") return } if result.isFinal { print("\(item) : \(result.bestTranscription.formattedString)") NotificationCenter.default.post(name: Notification.Name("goAndRead"), object: nil, userInfo: self.myDic) } } }
Posted
by SergioDCQ.
Last updated
.
Post not yet marked as solved
3 Replies
102 Views
Since iOS 16.1 we are getting crash reports that the the app is crashing when we call JSONDecoder.decode() using some Decodable as parameter. Those crashes are coming from two totally different parts of the app we have not changes for over a year. The one is our Restclient and the second the Lottie library. BACKGROUND THREAD 13 - CRASHED libobjc.A.dylib objc_msgSend CoreFoundation __exceptionPreprocess CoreFoundation __NSDictionaryI_new Foundation newJSONObject Foundation newJSONValue Foundation newJSONValue XX-App-AppStore XXRestClient.RestClientImpl.(decode in _A44A6D10715BFBCEC7551A9DE0CC1D8B)<A where A: Swift.Decodable>(_: Foundation.Data?, identifier: Swift.String) -> Swift.Result<A, XXRestClientAPI.RestClientError> RestClientImpl.swift:373 XX-App-AppStore closure #1 (Foundation.Data?, __C.NSURLResponse?, Swift.Error?) -> () in XXRestClient.RestClientImpl.(dataTask in _A44A6D10715BFBCEC7551A9DE0CC1D8B)<A where A: Swift.Decodable>(_: Foundation.URLRequest, identifier: Swift.String, handler: (Swift.Result<A, XXRestClientAPI.RestClientError>) -> ()) -> XXRestClientAPI.RestClientTask RestClientImpl.swift:229 The second stacktrace MAIN THREAD - CRASHED libobjc.A.dylib objc_msgSend CoreFoundation ____NSDictionaryI_new_block_invoke CoreFoundation __NSDictionaryI_new Foundation newJSONObject Foundation newJSONValue Foundation newJSONValue HC-App-AppStore function signature specialization <Arg[4] = Dead> of static Lottie.Animation.named(_: Swift.String, bundle: __C.NSBundle, subdirectory: Swift.String?, animationCache: Lottie.AnimationCacheProvider?) -> Lottie.Animation? AnimationPublic.swift:67 does anybody else experience similar issues? Is there a Bug in iOS 16.1 ?
Posted
by agiokas.
Last updated
.
Post not yet marked as solved
0 Replies
138 Views
Description I am working on a SwiftUI macOS application that has a 2FA prompt inside an alert, with SecureFields for the user to input their password and 2FA code. The SecureFields in the alert function fine as TextFields but are not obscured ('password' -> '********'), which raises a major security risk. I have tested the exact same code on iOS and the SecureFields are obscured as intended (see below screenshots). I believe this is a bug in macOS Ventura, I have tried updating to the 13.1 beta 3 and beta 4 but neither build fixes the issue. Any ideas on what to do here? Example Code: struct ContentView: View { @State private var alertShown: Bool = true @State private var username: String = "" @State private var password: String = "" var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundColor(.accentColor) Text("Hello, world!") } .padding() .alert("Sign In", isPresented: $alertShown, actions: { TextField("Username", text: $username) SecureField("Password", text: $password) Button("Submit", action: { print("Username: \(username), Password: \(password)") }) }) } } Compiled for macOS: Compiled for iOS:
Posted
by b521i9s.
Last updated
.
Post not yet marked as solved
0 Replies
55 Views
I’m looking to timestamp a file from within an iOS app using a TSA The OpenSSL route to do it would be e.g. openssl ts -query -data myFile.png -no_nonce -out myFile.tsq How can we do the same using Apple’s PKI equivalents on iOS using Swift?
Posted Last updated
.