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

Swift Documentation

Pinned Posts

Posts under Swift tag

2,521 Posts
Sort by:
Post not yet marked as solved
4 Replies
72 Views
Hi Devs, I'm new to coding and studying with an old course on Xcode 11. When building the application, a variable with its declaration is inserted in a line of the SceneDelegate file (let contentView = ) which however no longer exists. How is it resolved? I couldn't go on anymore. Thank you all.
Posted
by MoraxDev.
Last updated
.
Post not yet marked as solved
0 Replies
9 Views
We are running into a major issue with building an iOS Widget. iOS Widgets are basically large informational app icons you can pin to your iPhone home screen (What is a widget?). iOS widgets were introduced in iOS 14. We’ve finished building our iOS widget. However, when half of our users attempt to search for our widget after downloading our app, our widget is not showing up in the widget search results. For the other half, it works fine. This seems to be somewhat of a bug from Apple, as it is affects other widget apps (Apple Thread, the problem exists for large widget apps also). It seems like we are having this issue far more, percentage-wise, than other widget apps. I’ve searched through nearly every resource online (StackOverflow, etc.), which is why I’m posting a question now. Things like deleting the app and reinstalling, restarting the phone, etc. have not been a fix either for these problematic users. It doesn't seem to be tied to any iOS version (14, 15, etc.). As I have iOS 15, and it works fine. But, some users with iOS 15 are getting the bug. Has anyone ran into this issue where a widget is not searchable? How did you fix it? Any resources are appreciated as I am at a major blocker right now. Since my app is primarily based on iOS widgets, this makes it basically unusable for certain users.
Posted
by tlyf0824.
Last updated
.
Post not yet marked as solved
2 Replies
58 Views
Am going through a SwiftUI course, so the code is not my own. When I migrated my @Bindings into @Published items in an @ObservableObject I started getting the following error: Publishing changes from within view updates is not allowed, this will cause undefined behavior. The warning occurs in the ScannerView which is integrated with the main view, BarcodeScannerView. It occurs when an error occurs, and scannerView.alertItem is set to a value. However, it does not occur when I am setting the value of scannerView.scannedCode, and as far as I can tell, they both come from the sample place, and are the same actions. There are tons of posts like mine, but I have yet to find an answer. Any thoughts or comments would be very appreciated. BarcodeScannerView import SwiftUI struct BarcodeScannerView: View { @StateObject var viewModel = BarcodeScannerViewModel() var body: some View { NavigationStack { VStack { ScannerView(scannedCode: $viewModel.scannedCode, typeScanned: $viewModel.typeScanned, alertItem: $viewModel.alertItem) .frame(maxWidth: .infinity, maxHeight: 300) Spacer().frame(height: 60) BarcodeView(statusText: viewModel.typeScanned) TextView(statusText: viewModel.statusText, statusTextColor: viewModel.statusTextColor) } .navigationTitle("Barcode Scanner") .alert(item: $viewModel.alertItem) { alertItem in Alert(title: Text(alertItem.title), message: Text(alertItem.message), dismissButton: alertItem.dismissButton) } } } } BarcodeScannerViewModel import SwiftUI final class BarcodeScannerViewModel: ObservableObject { @Published var scannedCode = "" @Published var typeScanned = "Scanned Barcode" @Published var alertItem: AlertItem? var statusText: String { return scannedCode.isEmpty ? "Not Yet scanned" : scannedCode } var statusTextColor: Color { scannedCode.isEmpty ? .red : .green } } ScannerView import SwiftUI struct ScannerView: UIViewControllerRepresentable { typealias UIViewControllerType = ScannerVC @Binding var scannedCode : String @Binding var typeScanned : String @Binding var alertItem: AlertItem? func makeCoordinator() -> Coordinator { Coordinator(scannerView: self) } func makeUIViewController(context: Context) -> ScannerVC { ScannerVC(scannerDelegate: context.coordinator) } func updateUIViewController(_ uiViewController: ScannerVC, context: Context) { } final class Coordinator: NSObject, ScannerVCDelegate { private let scannerView: ScannerView init(scannerView: ScannerView) { self.scannerView = scannerView } func didFind(barcode: String, typeScanned: String) { scannerView.scannedCode = barcode scannerView.typeScanned = typeScanned print (barcode) } func didSurface(error: CameraError) { switch error { case .invalidDeviceinput: scannerView.alertItem = AlertContext.invalidDeviceInput case .invalidScannedValue: scannerView.alertItem = AlertContext.invalidScannedValue case .invalidPreviewLayer: scannerView.alertItem = AlertContext.invalidPreviewLayer case .invalidStringObject: scannerView.alertItem = AlertContext.invalidStringObject } } } }
Posted
by SergioDCQ.
Last updated
.
Post not yet marked as solved
0 Replies
39 Views
Hello my Xcode app fetches the current user from my database and stores their data in a User struct. And this data is needed for other portions of the app. I use an EnvirnmentObject to translate this data to other views. But the problem Im running in is: if I modify a variable in the struct of the current user in one view then navigate to another view this change is not observed in the new view. I don't think you can make @Published vars static, but what's another approach so that if I modify the variable "followers" for example in one view then all the others views will also have this change. I want to do this so I don't have to fetch the current user from the database every time I make changes to the current user. getting the current user: import SwiftUI import Firebase class AuthViewModel: ObservableObject{ private let service = UserService() @Published var currentUser: User? init(){ self.fetchUser() } func fetchUser(){ service.fetchUser() { user in self.currentUser = user } } } view 1 import SwiftUI struct viewOne: View { @EnvironmentObject var authViewModel: AuthViewModel var body: some View { VStack(alignment: .center, spacing: 2){ AuthViewModel.currentUser.followers = 25 } } } view 2 - change in followers var is not seen import SwiftUI struct viewOne: View { @EnvironmentObject var authViewModel: AuthViewModel var body: some View { VStack(alignment: .center, spacing: 2){ Text("\(AuthViewModel.currentUser.followers)") // not 25 } } }
Posted Last updated
.
Post not yet marked as solved
0 Replies
36 Views
Hello, I have an Xcode app with a few thousand users and I use firestore to store my data. Every time a user registers firestore creates a random uid for them. Right now I have all my users in one big collection called "users." I was thinking about splitting up this collection into sub collections for each letter in the alphabet and then putting each user, based on the first letter of their name, in the corresponding sub collection. But the only problem with this is when I want to fetch the current user. When a user signs into the app I only have their uid from the firestore authentication. So if I want to fetch the current user I wouldn't really have any pointer to which sub collection to look into. I thought of maybe putting a pointer letter at the beginning of the UID but I don't think firestore allows me to change Uids. Does anyone know a better approach to this or how I can make this work. Id appreciate the help.
Posted Last updated
.
Post not yet marked as solved
0 Replies
24 Views
I'm trying to add a divider, or some sort of line/border, to differentiate the main content on the screen and the content I've added uisng Section(footer: ). Anytime I try to add some sort of divider in FooterView, it goes right under where the footer meets the main content. And I haven't been able to find anything that allows me to add a border to where I create the footer. I've attached an image that shows what I'm talking about. Here is the code I currently have for creating the footer which I use in ContentView(): https://i.stack.imgur.com/L3WyG.jpg import SwiftUI struct ContentView: View { @State var selectedView = 0 var body: some View { Section(footer: FooterView(selectedView: $selectedView) ) { ZStack { Color.blue VStack { Spacer() if selectedView == 0 { Text("selected view = 0") } else { Text("selected view = 1") } } }.ignoresSafeArea(.all) } } } struct FooterView: View { let NoData = ["No Data displayed" : ["Nothing to show"]] @Binding var selectedView: Int //for checking screen is big enough to fit footer without padding @State var isLargeDevice: Bool = { if UIScreen.main.bounds.height > 800 { return true } else { return false } }() var body: some View { if isLargeDevice{ VStack{ Divider() HStack { Button(action: { // set selected view to 0 when the left button is clicked selectedView = 0 }, label: { Image(systemName: "fork.knife") .font(.title2) .foregroundColor(selectedView == 0 ? Color("NavBar color") : .primary) }).frame(maxWidth: .infinity) Button(action: { // set selected view to 1 when the right button is clicked selectedView = 1 }, label: { Image(systemName: "heart.fill") .font(.title2) .foregroundColor(selectedView == 1 ? Color("NavBar color") : .primary) }).frame(maxWidth: .infinity) } } } else { ZStack{ VStack{ Divider() HStack { Button(action: { // set selected view to 0 when the left button is clicked selectedView = 0 }, label: { Image(systemName: "fork.knife") .font(.title2) .foregroundColor(selectedView == 0 ? Color("NavBar color") : .primary) }).frame(maxWidth: .infinity) Button(action: { // set selected view to 1 when the right button is clicked selectedView = 1 }, label: { Image(systemName: "heart.fill") .font(.title2) .foregroundColor(selectedView == 1 ? Color("NavBar color") : .primary) }).frame(maxWidth: .infinity) } } } .padding() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } I tried using .overlay, a super thin rectangle, divider(), the padding modifier to see if that would help, but none have worked so far.
Posted
by rsehgal.
Last updated
.
Post not yet marked as solved
2 Replies
597 Views
I have UIViewController with NavigationBar that is a part of UITabController. Inside UIViewController I have only UITableView. NavigationBar is transparent and blurred. TableView top constraint is to superview, so when I scroll content it goes behind navigation bar. Problem: loadData data triggered immediately when I start to scroll down. Right after I scroll few pixels down. All works fine if I remove largeTitles, but with large titles it feels like refreshControl already at position when it ready to trigger .valueChanged Also it works fine if to remove tab bar and load navigationController directly as root. But I need tabbar. Full code: @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let window = UIWindow(frame: UIScreen.main.bounds) window.makeKeyAndVisible() self.window = window window.rootViewController = TabBarController() return true } } class TabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() let navigationController = UINavigationController(rootViewController: ViewController()) navigationController.navigationBar.prefersLargeTitles = true viewControllers = [navigationController] } } class ViewController: UIViewController { private let tableView = UITableView() private let refreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Test" view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalToSuperview() } tableView.delegate = self tableView.dataSource = self tableView.refreshControl = refreshControl refreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged) } @objc func loadData() { print("loadData triggered") DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { self.refreshControl.endRefreshing() } } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell if let defaultCell = tableView.dequeueReusableCell(withIdentifier: "defaultCell") { cell = defaultCell } else { cell = UITableViewCell(style: .value1, reuseIdentifier: "defaultCell") } cell.textLabel?.text = "Test" return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 10 } } BUT Everything works fine if same thing done from StoryBoard:
Posted
by dbyst.
Last updated
.
Post not yet marked as solved
2 Replies
615 Views
Since Xcode does symbolize the app (written in swift and distribute to enterprise) while generating the .ipa, is code obfuscation still necessary ? The reason the team is considering the obfuscation is security is the highest priority to us, we have lots of algorithms within the app and we don't want it has any chance to be reverse engineered or expose human readable source code. Thank you, Richard
Posted
by dffffwew.
Last updated
.
Post not yet marked as solved
2 Replies
47 Views
Hi, with my new iMac I want to continue learning swift, I was told that the playground is a good tool and I trust. I got the Xcode/New/Playground file and wrote some code - see it : ```import Cocoa var greeting = "Hello, playground" for i in 1...10{ print (i) } The same code runs on Xcode 9.2 (9C40b) I can't help myself 🥲 Uwe Edit: I downloaded Michael Kofler's Swift 5 examples and they even did not run
Posted Last updated
.
Post not yet marked as solved
6 Replies
101 Views
Hi there! I have an issue with UI when updating items in Core Data. Let's say I have three screens A, B and C where A --> B --> C. On screen A, I have a tableView with items from Core Data. On screen C, I have to make some changes on items of Core Data such as update or remove them. So, when I go back to screen A and refresh the tableView in order to get the updated list, the UI is not updated. I debugged the code and I can see that Core Data are correctly updated. Do you know what the issue is and why the UI is not updated but Core Data is up to date?
Posted Last updated
.
Post not yet marked as solved
10 Replies
1.2k Views
Recently I updated to Xcode 14.0. I am building an iOS app to convert recorded audio into text. I got an exception while testing the application from the simulator(iOS 16.0). [SpeechFramework] -[SFSpeechRecognitionTask handleSpeechRecognitionDidFailWithError:]_block_invoke Ignoring subsequent recongition error: Error Domain=kAFAssistantErrorDomain Code=1101 "(null)" Error Domain=kAFAssistantErrorDomain Code=1107 "(null)" I have to know what does the error code means and why this error occurred.
Posted Last updated
.
Post not yet marked as solved
1 Replies
46 Views
GOAL: I want to UI test my SegmentedControl - check that each segment is selected when tapped on it CONTEXT: The shoeType UISegmentedControl has 3 segments [City, Running, Baskets] CODE: Here is my code: ViewController.swift : @IBOutlet weak var shoeType: UISegmentedControl! ViewControllerUITest.swift: func testSegmentedControl_WhenTapped_ChangeSegment() { app.launch() let shoeTypeSegmentedControl = app.segmentedControls["city"] app.segmentedControls["city"].tap() XCTAssertEqual(shoeTypeSegmentedControl.label, "City") }
Posted Last updated
.
Post not yet marked as solved
0 Replies
52 Views
Im working on project where I am want to use DNSProxy network extension to our app in iOS and Mac OS. We are able to add DNSProxy extension successfully and getting the call in startProxy and handleNewFlow Method of DNSProxyProvider in iOS. But I have big confusion on the steps and followed used to process the flow and pass it to datagrams and entire implementation. Here is my confusion: I have my own DNS resolver API which takes name of remoteHostName as query parameter and return the response in JSON. First confusion is as per the DNSProxy Documentation every flow needs to processed through these steps, openLocaleEndpoints, ReadDataGrams, outboundCopier (Read in some developer threads), InboundCopiers and finally to WriteDataGrams. Am I correct here? If above steps are correct, to process each flow then how can I use my own DNS API resolver in between these predefined steps. and How and where to use that response data sent my custom DNS API? Currently when Im making DNSProxy active then immediately device internet connection getting interrupted, this might be because we are not hanging the flow properly in handleNewFlow Method. Am I correct here?
Posted
by Mash86.
Last updated
.
Post not yet marked as solved
2 Replies
47 Views
My project was working 100% fine on xcode13 but when i updated my MAC OS from big sur to monterey and my Xcode from 13 to 14. my app crashes on start. and below are the highlighted error pages and screen shots Please let me know any possible solution to make the app it run
Posted Last updated
.
Post not yet marked as solved
0 Replies
23 Views
Hello. I'm writing a generic Picker view and would like to pass the required PickerStyle to the view. Can anyone tell me how to pass PickerStyle as an argument? Thank you
Posted
by AKTuohy.
Last updated
.
Post marked as solved
9 Replies
6.4k Views
Background: I have been stuck on this annoying problem for days, trying different solution and searching apple developer forum, stackoverflow etc for answers; some have had similar problems but no suggested solution had the desired effect. The problem is that when updating an observableObject or environmentObject down the navigation hierarchy view stack, the views get popped back to root. Viewing data from observableObject is fine, but not editing. Scenario is: I navigate to: root -> view1 -> view2. I update the environmentObject in View2 but then I get pushed back to: root -> view1 I have simplified my app in order to make it more understandable. See below: ObservableObject: class DataStore: ObservableObject { static let shared = dataStore() @Published var name : Int = "" } RootView: struct ContentView: View { @StateObject var dataStore = DataStore.shared @State private var isShowingView1 = false var body: some View { NavigationView{ VStack{ Text(dataStore.name) NavigationLink(destination: View1(), isActive: $isShowingView1) { } Button(action: { isShowingView1 = true }) } } } } View1: struct View1: View { @EnvironmentObject var dataStore: dataStore @State private var isShowingView2 = false var body: some View { ScrollView{ VStack(alignment: .center) { Text(dataStore.name) NavigationLink(destination: View2(), isActive: $isShowingView2) { } Button(action: { isShowingView2 = true }){ Text("Go to View2") } } } } } View2: struct View2: View { @EnvironmentObject var dataStore: dataStore var body: some View { ScrollView{ VStack(alignment: .center) { Text(dataStore.name) Button(action: { dataStore.name = "updated value" }){ Text("Update data") } // When updating this environmentObject the viewstack will be pushed back to View1. If view2 had been navigated to view3 and the view3 had been updating the environmentObject, then it would also be pushed back to View1. } } } } Solution: I spent many hours searching for solutions and trying different approaches, but nothing I tried worked. There seemed to be a few other people that had the same problem as I experienced, but the suggested solutions didn't cut it. But then I stumbled on a solution for this problem when trying to implement another feature. So to be frank I am writing here now, not to ask this great community for help, but instead to give back to the community by providing the this solution to others that might need to see this. The solution is really simple implement but was not so easy to come across. If you experience a problem similar to me then you will only need to update your rootView accordingly: RootView Updated: struct ContentView: View { @StateObject var dataStore = DataStore.shared @State private var isShowingView1 = false var body: some View { NavigationView{ VStack{ Text(dataStore.name) NavigationLink(destination: View1(), isActive: $isShowingView1) { } Button(action: { isShowingView1 = true }) } } .navigationViewStyle(.stack) //ADD THIS LINE ABOVE } } This one line .navigationViewStyle(.stack) fixed the problem of popping the viewstack for me. Unfortunately I can't provide you with the logic explanation for this behaviour, but it works and I am satisfied with that. Perhaps you are too, or perhaps you have insight on why this solution actually achieves the desired effect of allowing views down the hierarchy update observableObjects without being popped. Happy coding :)
Posted
by SirWitten.
Last updated
.
Post not yet marked as solved
0 Replies
30 Views
I want to print documents using UIPrintIntrectionController() and need to pass one of the available printer but i have to pass the printer programmatically instead of hardcoding the details of printer i tried using NetServiceBrower() but it is depreceted and resources are not available about it `let printController = UIPrintInteractionController.shared let printInfo = UIPrintInfo(dictionary: nil) printInfo.jobName = "printing" printInfo.outputType = UIPrintInfo.OutputType.general printController.printInfo = printInfo let str = "hello" let dataStr: Data = Data(str.utf8) let data = NSData(data: dataStr) printController.printingItem = data //need to access a printer to pass to printerController let printer = ?? printController.print(to: printer)
Posted
by Abhshek.
Last updated
.
Post not yet marked as solved
0 Replies
33 Views
Hello all, I'm currently trying out the Google Sign-In (using firebase) feature for the first time - I'm following a tutorial, that's why you can see a few 'pointers' near the end of the code - and I have been greeted with an error: "Cannot find 'view' in scope" on line 48. I'd really appreciate it if someone could solve this, thanks! import GoogleSignIn import Firebase import FirebaseAuth struct LoginScreen: View { @State var username: String = "" @State var password: String = "" var body: some View { VStack { VStack { LoginHeader() .padding(.bottom) CustomTextfield(text: $username) CustomTextfield(text: $username) HStack { Spacer() Button(action: {}) { Text("Forgot Password?") } } .padding(.trailing, 24) CustomButton() Text("or") .padding() GoogleSiginBtn { guard let clientID = FirebaseApp.app()?.options.clientID else { return } let config = GIDConfiguration(clientID: clientID) GIDSignIn.sharedInstance.configuration = config GIDSignIn.sharedInstance.signIn(withPresenting: view.getRootViewController()) { signResult, error in if let error = error { ...{ return } } guard let user = signResult?.user, let idToken = user.idToken else { return } let accessToken = user.accessToken let credential = GoogleAuthProvider.credential(withIDToken: idToken.tokenString, accessToken: accessToken.tokenString) // Use the credential to authenticate with Firebase Auth.auth().signIn(with: credential) { authResult, error in } } } // GoogleSiginBtn } // VStack .padding(.top, 52) Spacer() } } } struct LoginScreen_Previews: PreviewProvider { static var previews: some View { LoginScreen() } }
Posted
by DanGL.
Last updated
.
Post not yet marked as solved
1 Replies
119 Views
Hi! We've recently released an usual app-update, but suddenly got a bunch of crashes in App Store Connect and almost none in Firebase Crashlytics. According to customer support, for some users the app insta-crashes. A white screen appears for a flash and then they're returned to the home screen. The app always insta-crashes, only a reinstall fixes it. It makes sense while Crashlytics isn't reporting any crashes, because it doesn't even get a chance to run and upload the crash reports to their server. The Xcode organizer does show a bunch of crashes, but with no stack trace. It just says MyApp: NO_CRASH_STACK. Looking at the explicit 'xccrashpoint' in Finder reveals a couple of crash reports, that I've attached, but they're not that useful. As far as I can tell, the app crashes while it's trying to load the Swift core, that's embedded in the app, but I'm not sure why that would cause a crash. Maybe it was supposed to use the library embedded in iOS (/usr/lib/swift/libswiftCore.dylib)? Any help would be greatly appreciated 🍺! report.crash
Posted
by adiracu.
Last updated
.
Post not yet marked as solved
4 Replies
244 Views
I have a NavigationSplitView in my app, I have an @State variable in my detail view that gets created in init. When I select something from the sidebar and the detail view renders, at first everything looks ok. But when I select a different item on the sidebar, the contents of the @state variable don't get recreated. Using the debugger I can see the init of the detail view get called every time I select a new item in the sidebar, and I can see the @State variable get created. But when it actually renders, the @State variable still contains the previous selection's values. I've reduced this problem to a test case I'll paste below. The top text in the detail view is a variable passed in from the sidebar, and the second line of text is generated by the @State variable. Expected behavior would be, if I select "one" the detail view would display "one" and "The name is one". If I select "two" the detail view would display "two" and "The name is two". Instead, if I select "one" first, it displays correctly. But when I select "two", it displays "two" and "The name is one". Note that if I select "two" as the first thing I do after launching the app, it correctly displays "two" and "The name is two", but when I click on "one" next, it will display "one" and "the name is two". So the state variable is being set once, then never changing again, Here's the sample code and screenshots: import SwiftUI struct Item: Hashable, Identifiable { var id: Self {self} let name: String } struct ContentView: View { var items: [Item] @State private var selectedItem: Item? = nil init() { self.items = [Item(name: "one"), Item(name: "two"), Item(name: "three")] } var body: some View { NavigationSplitView{ List(selection: $selectedItem) { ForEach(items) { item in Text(item.name) } } } detail: { if let name = selectedItem?.name { DetailView(name: name) } else { Text("Select an item") } } } } struct DetailView: View { @State var detailItem: DetailItem var name: String init(name: String) { self.name = name _detailItem = State(wrappedValue: DetailItem(name: name)) } var body: some View { VStack { Text(name) Text(detailItem.computedText) } } } struct DetailItem { let name: String var computedText: String { return "The name is \(name)" } }
Posted Last updated
.