/r/swift

Photograph via snooOG

Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

ATTN! Looking for work or to hire? Check out r/SwiftJobs!


About:

Dedicated to the Swift programming language released by Apple. More info in the Swift Wiki.

Please, check the FAQs before submitting.


IRC Chatrooms:

General Swift Discussion

irc.freenode.net #swift-lang

Cocoa/Cocoa Touch Discussion

irc.freenode.net #cocoa-init

Related Subreddits:


Keywords: swift, swiftlang, ios, os x, apps, apple, mac, iphone, ipad

/r/swift

120,836 Subscribers

0

No ObservableObject of Type "" found.

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.

where the error occurs

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

2 Comments
2024/11/09
18:21 UTC

0

Looking for Swift developer (IPhone app)

Need help with Swift development (IPhone app).

5 Comments
2024/11/09
17:15 UTC

1

Dynamic scoping for global variables in Swift?

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.

7 Comments
2024/11/09
14:12 UTC

0

Maximum length of labels

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.

7 Comments
2024/11/09
04:04 UTC

4

image description CoreML?

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?

2 Comments
2024/11/08
22:47 UTC

2

Can Task { print(“hello”) } be assigned to run on the main thread ?

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 ?

19 Comments
2024/11/08
22:05 UTC

3

Get Media Data from Another App or System

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

  1. get playing audio data from the phone
  2. media controls (forward, backward, play, pause)
  3. volume control

Which ones are the components to do so?

https://preview.redd.it/4bsgyis3zpzd1.jpg?width=1179&format=pjpg&auto=webp&s=cfed1423d6549a50157aea198c6cf2510f66d844

0 Comments
2024/11/08
18:19 UTC

3

How do you safely use AsyncThrowingStream with snapshotListener

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.

8 Comments
2024/11/08
17:24 UTC

1

Do I need Appsflyer for tracking?

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?

0 Comments
2024/11/08
17:20 UTC

15

Best APIs for an Event/PubSub system in 2024?

In the Swift standard libraries I've found many options, but all seem to be unofficially deprecated, or functionally incomplete.

  1. closure callbacks (avoid due to callback hell)
  2. SwiftUI Observable class injected into root Environment (ok for SwiftUI Views, unusable in non-UI code)
  3. NotificationCenter (replaced by Combine)
  4. Combine (replaced by Swift Concurrency)
  5. DispatchQueues (also replaced by Swift Concurrency)
  6. Swift Concurrency (No AsyncStream support for multicast/broadcast) (seems to be some unofficial work in progress here: https://github.com/apple/swift-async-algorithms/pull/242)

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:

  • When triggered, display toast banner over the main UI with the message
  • Automatically dismiss itself after a few seconds
  • Any subsequent submitted messages get queued and displayed in FIFO order.
  • Subscriptions are loosely coupled
  • Runs within a single iOS application
  • Multi-consumer (e.g. also a logger or telemetry client)
  • A variety of long-running async tasks can submit status messages

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).

3 Comments
2024/11/08
15:54 UTC

2

Protecting against bundled files being accessible on MacOS when installing iOS apps?

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?

3 Comments
2024/11/08
12:40 UTC

2

Build a Live Activity Broadcast Election Results iOS App | Firestore DB | Cloud Functions | APNS

0 Comments
2024/11/08
11:59 UTC

1

Is The Unwrap Variable Linked To Its Original Variable Hence Reflecting Updates

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
  }
}
3 Comments
2024/11/08
07:05 UTC

12

SwiftUI Map: why does ForEach work but Array does not?

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.

3 Comments
2024/11/08
04:28 UTC

8

I developed a journaling app to finally get back into a habit I loved as a kid – would love some harsh feedback

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:

  • Voice Recordings: I started with Apple’s Voice Memos, but it quickly became a chaotic mess of files, making it hard to find anything. It even led to some awkward moments when others noticed - my ex-girlfriend calling me borderline weird.
  • Speech-to-Text Notes: Switching to speech-to-text in the Notes app seemed like a solution, but after a year of daily entries, it turned into an unmanageable collection of “Untitled” notes.
  • Alternatives: After a year of looking for alternatives and exploring apps like Notion, I noticed a huge gap in this vertical.

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!

1 Comment
2024/11/07
21:55 UTC

5

How can I access the Italian App Store to see my app feature and take a screenshot?

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!

https://preview.redd.it/b3xbamwu7jzd1.png?width=212&format=png&auto=webp&s=313bf5b93657006a504148b66c6415da5d39047f

https://preview.redd.it/a7hm3gaw7jzd1.png?width=671&format=png&auto=webp&s=6af27651d92fe6a4170c76264abb8d8919024f6d

9 Comments
2024/11/07
19:35 UTC

1

How Can I Ensure My App Looks Consistent Across All iPhone Models?

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!

2 Comments
2024/11/07
18:21 UTC

1

Local Storage for HealthKit data?

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?

3 Comments
2024/11/07
14:24 UTC

4

Firebase Authentication with The Composable Architecture

1 Comment
2024/11/07
14:18 UTC

3

UI integration doesn’t look too difficult, but I am wondering how I can achieve what X is doing when suggesting the user to refresh for new content from Firebase (for example). Any ideas?

3 Comments
2024/11/07
08:17 UTC

13

Getting Started with Swift Data - A Beginner's Guide

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.

What is Swift Data?

Swift Data is a framework that allows you to:

  • Store data persistently on device
  • Define your data model using simple Swift classes
  • Automatically save changes
  • Query and filter data efficiently
  • Work seamlessly with SwiftUI

Prerequisites

  • 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

1 Comment
2024/11/07
05:51 UTC

5

Got an interview with an iOS team coming up

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!

6 Comments
2024/11/07
05:37 UTC

3

How to begin learning swift?

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?

16 Comments
2024/11/07
01:46 UTC

46

Hey, all. Is there a Swift open source scene?

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!

25 Comments
2024/11/06
23:56 UTC

3

ScreenCaptureKit requires permission to record video every time I recompile

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.

5 Comments
2024/11/06
21:04 UTC

20

I have physical live coding interview tomorrow and I am not sure what to expect.

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.

9 Comments
2024/11/06
17:24 UTC

4

Always enabling Strict Concurrency Checking

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 ?

6 Comments
2024/11/06
16:28 UTC

Back To Top