/r/swift
Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.
Dedicated to the Swift programming language released by Apple. More info in the Swift Wiki.
Please, check the FAQs before submitting.
General Swift Discussion
irc.freenode.net #swift-lang
Cocoa/Cocoa Touch Discussion
irc.freenode.net #cocoa-init
Keywords: swift, swiftlang, ios, os x, apps, apple, mac, iphone, ipad
/r/swift
Im building an recipe app for the social media of my mother. i already have the functionality for the users, when a user gets created an empty array gets initiated at the database named favoriteRecipes, which stores the id of his favorite recipes to show in a view.
This is my AuthViewModel which is relevant for the user stuff:
import Foundation
import Firebase
import FirebaseAuth
import FirebaseFirestore
protocol AuthenticationFormProtocol {
var formIsValid: Bool { get }
}
u/MainActor
class AuthViewModel : ObservableObject {
u/Published var userSession: FirebaseAuth.User?
u/Published var currentUser: User?
u/Published var currentUserId: String?
init() {
self.userSession = Auth.auth().currentUser
Task {
await fetchUser()
}
}
func signIn(withEmail email: String, password: String) async throws {
do {
let result = try await Auth.auth().signIn(withEmail: email, password: password)
self.userSession = result.user
await fetchUser() // fetch user sonst profileview blank
} catch {
print("DEBUG: Failed to log in with error \(error.localizedDescription)")
}
}
func createUser(withEmail email: String, password: String, fullName: String) async throws {
do {
let result = try await Auth.auth().createUser(withEmail: email, password: password)
self.userSession = result.user
let user = User(id: result.user.uid, fullName: fullName, email: email)
let encodedUser = try Firestore.Encoder().encode(user)
try await Firestore.firestore().collection("users").document(result.user.uid).setData(encodedUser)
await fetchUser()
} catch {
print("Debug: Failed to create user with error \(error.localizedDescription)")
}
}
func signOut() {
do {
try Auth.auth().signOut() // sign out user on backend
self.userSession = nil // wipe out user session and take back to login screen
self.currentUser = nil // wipe out current user data model
} catch {
print("DEBUG: Failed to sign out with error \(error.localizedDescription)")
}
}
func deleteAcocount() {
let user = Auth.auth().currentUser
user?.delete { error in
if let error = error {
print("DEBUG: Error deleting user: \(error.localizedDescription)")
} else {
self.userSession = nil
self.currentUser = nil
}
}
}
func fetchUser() async {
guard let uid = Auth.auth().currentUser?.uid else { return }
currentUserId = uid
let userRef = Firestore.firestore().collection("users").document(uid)
do {
let snapshot = try await userRef.getDocument()
if snapshot.exists {
self.currentUser = try? snapshot.data(as: User.self)
print("DEBUG: current user is \(String(describing: self.currentUser))")
} else {
// Benutzer existiert nicht mehr in Firebase, daher setzen wir die userSession auf nil
self.userSession = nil
self.currentUser = nil
}
} catch {
print("DEBUG: Fehler beim Laden des Benutzers: \(error.localizedDescription)")
}
}
}
This is the code to fetch the favorite recipes, i use the id of the user to access the collection and get the favoriteRecipes out of the array:
import FirebaseFirestore
import SwiftUI
class FavoriteRecipeViewModel: ObservableObject {
u/Published var favoriteRecipes: [Recipe] = []
u/EnvironmentObject
var viewModel: AuthViewModel
private var db = Firestore.firestore()
init() {
Task {
await fetchFavoriteRecipes()
}
}
func fetchFavoriteRecipes() async{
let userRef = db.collection("users").document(viewModel.userSession?.uid ?? "")
do {
let snapshot = try await userRef.collection("favoriteRecipes").getDocuments()
let favoriteIDs = snapshot.documents.map { $0.documentID }
let favoriteRecipes = try await fetchRecipes(recipeIDs: favoriteIDs)
} catch {
print("DEBUG: Failed to load favorite recipes for user: \(error.localizedDescription)")
}
}
func fetchRecipes(recipeIDs: [String]) async throws -> [Recipe] {
var recipes: [Recipe] = []
for id in recipeIDs {
let snapshot = try await db.collection("recipes").document(id).getDocument()
if let recipe = try? snapshot.data(as: Recipe.self) {
recipes.append(recipe)
}
}
return recipes
}
}
Now the Problem occurs at the build of the project, i get the error
SwiftUICore/EnvironmentObject.swift:92: Fatal error: No ObservableObject of type AuthViewModel found. A View.environmentObject(_:) for AuthViewModel may be missing as an ancestor of this view.
I already passed the ViewModel instances as EnvironmentObject in the App Struct.
u/main
struct NimetAndSonApp: App {
u/StateObject var viewModel = AuthViewModel()
u/StateObject var recipeViewModel = RecipeViewModel()
u/StateObject var favoriteRecipeViewModel = FavoriteRecipeViewModel()
u/UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(viewModel)
.environmentObject(recipeViewModel)
.environmentObject(favoriteRecipeViewModel)
}
}
}
I cant work out what the problem is
Need help with Swift development (IPhone app).
Is there any way in Swift to create a global variable with dynamic scoping? By this I mean you set a variable to some value within a local scope, and it keeps that value not only in that local scope, but also in any scopes that fall below that scope. So you can call other functions, and they can call other functions, and the variable retains the value without needing to be passed explicitly, just like any global variable. But above the scope where you set the variable, it doesn't have that value.
AFAIK, Swift doesn't have this capability, but I'm curious, as it would be useful for cases where I have several instances of an algorithm running in parallel, and I'd like them each to have access to their own instance of a global variable. Obviously in an ideal world you don't need global variables at all, but sometimes that is difficult or infeasible.
Thanks.
I have a line made up of a label and a button. The label changes, but I don't want to have the location of the button change, I would like to have more space after a short label than a long one.
If I have a fixed list of values for the label is there some way of finding the maximum length without having to set the label to each of the values and then getting the length?
It's more than just the length of the label in characters since AVAVAV and AAAVVV are both 6 characters but, with kerning, AVAVAV is shorter.
I know the easy way is to change the line so the button is first and the label can be as long as it wants, but I am a masochist and I really want the label first and I don't like the button moving around and I don't like leaving more space than I need for the longest label.
Hey guys do someone have an ideer how to make “image description”.
I’m a noob to Xcode and all that, I have tried to build a view in my macOS app where i chooes a folder to scan for photos and videos and the app will auto automatisk make a image description to each based on the image’s content and my dream was so I could search in the app for af specific photo or video just by describe it.
Is there a Ai model that can do that?
Hi,
I’m curious to know if Task { } running in a non MainActor context can be assigned to the main thread ?
As I understand all these tasks are assigned randomly to a thread from a pool of threads and although adding @MainActor to it guarantees to run on the Main Thread,
Writing it like above guarantees it won’t be asaigned to run to the Main Thread ?
This is a screenshot from Sony Sound Connect (app to manage my headphones)
I am looking for what handles the highlighted area
Audio is playing from Spotify (it could be youtube, prime music, or any other audio playing in the background)
I need to
Which ones are the components to do so?
I am using a AsyncThrowingStream to handle the stream of data that comes from firestore snapshot listener and for now my code works and looks like this:
func AddAsyncListenerForUserFavoriteProducts(userId: String) -> AsyncThrowingStream<[UserFavoriteProduct], Error> {
AsyncThrowingStream { continuation in
userFavoriteProductCollection(userId: userId).addSnapshotListener { querySnapshot, error in
//1. get documents
guard let documents = querySnapshot?.documents else {
print("Error fetching documents: \(error!)")
return
}
//2. map the documents data to a products array
let products: [UserFavoriteProduct] = documents.compactMap { documentsnapshot in
return try? documentsnapshot.data(as: UserFavoriteProduct.self)
}
continuation.yield(products)
}
}
}
i am calling this from a Task in my viewModel, obviously this code isnt safe for now because if the user leaves the screen neither the continuation nor snapshotlistener gets detroyed, I can't find online an example of how to handle this cleanly.
Developing my first IOS app which I’ll promote with ads on Meta, TikTok etc.
Do I need a third-party software like Appsflyer for attribution tracking or can I just connect SDK’s directly to my app and read the data within Meta, TikTok etc?
In the Swift standard libraries I've found many options, but all seem to be unofficially deprecated, or functionally incomplete.
Sooo... is everyone migrating to the new shiny before it's functionally complete?
Or am I missing something (very likely, I've only been at this for 1 year)?
How would you implement this today?
FYI I'm only targeting iOS 17+ with Swift 6 strict concurrency on.
/End of Question
-----
/Begin more Context
To put this into terms of a concrete example... I just want to write a simple "toast" banner system to display temporary in-app notifications to my users.
Example messages:
- "Some long running task completed"
- "Some database operation failed"
- "Some network request failed"
- "Some device you connect is now disconnected"
- etc.
Basic Requirements:
In essence, just a simple buffered async multicast Pub/Sub system that allows me to push messages onto a global queue which then notifies any component interested.
Coming from a JavaScript background, this would be trivial.
Given all the context, maybe there's another solution I haven't thought about?
(I'm aware there are probably 3rd party Toast libraries, but I'm generally curious b/c I need this pattern for other use-cases too).
Since the introduction of Apple allowing iOS apps on the Appstore to be installed and run on MacOS I have noticed that files such as my audio and image files can be seen, accessed and copied from the apps Cache on MacOS. This was probably partially accessible on iOS as it was but was nowhere near as easy.
Do you guys know of any or have used any way of preventing these files from appearing or being accessed from the MacOS cache of the app?
How do i directly update the audioSession variable or is the hasSession unwarp variable going to update it ? Im kind of confused can someone help?
private var audioSession: AVAudioSession?
...
func Execute()->{
audioSession = AVAudioSession.sharedInstance()
guard let hasSession = audioSession else {return}
do{
try hasSession.setCategory(.playAndRecord, mode: .default)
try hasSession.setActive(true) // Do these update audioSession directly or not at all
} catch{
//Errors
}
}
I'm trying to understand why the ForEach here works:
MapReader { reader in
Map(position: $mapCameraPosition.end) {
ForEach(markers) { marker in
if let coords = marker.coords {
ForEach(coords) { array in
MapPolygon(array)
}
}
}
}
}
But the array here gives at error of Trailing closure passed to parameter of type 'Binding<MapFeature?>' that does not accept a closure
:
MapReader { reader in
Map(position: $mapCameraPosition.end) {
ForEach(markers) { marker in
if let coords = marker.coords {
for array in coords {
MapPolygon(array)
}
}
}
}
}
I've got to say that the error - like so many SwiftUI errors is not at all informative and in fact is incorrect.
I see that ForEach
doesn't return a View
but does conform to DynamicViewContent
under certain circumstances.
Anyway, my code (ForEach) is working, but I'm just trying to undestand why it works.
Thanks.
Hey everyone,
I wanted to share a project I’ve been working on and get some feedback from this awesome community that I owe a lot.
A couple of years ago, I started learning Swift as a way to cope with the stress from various high-demand jobs I was juggling. Coding became a lifeline for me, and along with my co-founder (who was equally burnt out), we decided to embark on a side project that felt meaningful—a journaling app.
The Journey:
As a kid, I kept a diary and loved it. It was a simple way to process my thoughts and emotions. However, as life got busier, I lost the habit. I tried picking it up again but found it frustrating:
That’s when I thought, “Why not create it myself?” With the help of my co-founder, we aimed to design a simple, effective journaling app with a solid speech-to-text feature (surprisingly it was hard to find technically - we even ended up paying for ChatGPT’s API because Apple or Google wasn’t cutting it).
Here is the final product: https://apps.apple.com/us/app/journie-daily-diary-journal/id6737518223
We spent six months developing this app, pushing ourselves beyond the original timeline to add features like photos and audio recordings. I’ve kept the layout simple, just like my journal entries: text at the top, images below, and drawings at the bottom. It’s minimal, but I’d love to hear from others if this setup would work for them or if more customization would be helpful.
I’m not asking for downloads or subscriptions; I genuinely just want feedback from people who love journaling as much as I do. Would this app be something you’d use? What’s missing? What do you look for in a journaling app? I’d really appreciate any insights!
My app was recently featured on the Italian App Store according to AppFollow and AppFigures, and I’d like to see it myself and take a screenshot. I’m based outside of Italy and wondering if there’s a way to access the Italian App Store specifically to view this feature.
Has anyone else tried this before? Are there steps I can take to change my App Store region temporarily, or perhaps another way to view international App Store features?
Thanks in advance for any help!
I'm trying to optimize the UI of my iOS app to look the same on every iPhone model. Does anyone have recommendations for current resources, like courses, YouTube tutorials, or articles that focus on this? Most of what I've encountered discusses UIKit, but I'm looking for recent content, perhaps with a focus on SwiftUI. Any guidance would be greatly appreciated!
It's a pretty straight forward question, but should I store my HealthKit data locally as well (within SwiftData), or should I just store in HealthKit and read/write as needed?
Swift Data is Apple's newest framework for data persistence, introduced in iOS 17. It provides a modern, Swift-first approach to storing and managing data in your iOS applications. In this tutorial, we'll explore Swift Data from the ground up with practical examples.
Swift Data is a framework that allows you to:
Xcode 15 or later
iOS 17 or later
Basic understanding of SwiftUI
Here the full tutorial:
https://www.iosappfinder.com/blog/Swift-Data-a-Beginner-Guide
Hi all,
I applied for an internship and I made it to the final round! However, it's going to be an hour long panel with the iOS team. Any idea what questions to expect so I can prepare for them? They mainly work with SwiftUI, so I don't think any UIKit will be asked. Thanks!
I’ve been doing c# web development for many years. Recently got some urge to learn a new language/platform and got my self a Mac Studio.
What is a good way to start learning iOS and swift? Is there any good book or trainings material I should be going through before I jump in?
Hey, I've been a coder for more than 40 years now and I recently got dumped into early retirement. I had a couple of open source Mac projects written in Objective C in the late 90s early 00s but, you know, life.
So now I'm thinking about teaching myself Swift but the whole Apple Developer ecosystem is quite intimidating. Is that true? I'm not interested in writing stuff to sell, do I really need to buy a developer license?
EDIT: Thanks for all the encouragement, guys. I will definitely be installing XCode on my M4 MBP when it arrives on Friday!
I'm exploring using ScreenCaptureKit on MacOS, and overall I like it a lot. However, I've noticed one major drawback. I'm not trying to develop an app--I'm using Swift to run computer science experiments. As such, I edit my code and recompile all the time. Unfortunately, when I do this, the program loses permission to record video. I have to go back in system settings and give it permission for "Screen & System Audio Recording." Worse, the old version of the program with the same name still is there, so first I have to remove that, then run my program again, then add the new one.
Does anyone know if there's a trick to make the system settings recognize that my program is the same, even after recompiling? Or is there some (probably insecure) way to tell the system that apps should always have permission to record?
Thanks.
Hi
I had a theoritical interview on Monday and I was told there would be physical live coding where I would "need to fix" the project and after that explain my thinking behind it.
I am just really not sure what to expect (probably not LC style questions right) and the physical aspect of it (not working with my laptop, maybe not even with Xcode) kinda weirds me out as I have never done interview in physical setting.
Interview is for Junior/Mid level role.
Thank you, any tips will be much appreciated.
Hey guys,
Now that we have Strict Concurrency Checking should we enable that for all projects just to be safe ?
Also, is it guaranteed that using the modern swift concurrency with this check enabled wr will always see warnings or errors in vase of data race conditions, dead locks , etc other threading related problems ?