As I migrate my apps to Swift 6 one by one, I am gaining a deeper understanding of concurrency. In the process, I am quite satisfied to see the performance benefits of parallel programming being integrated into my apps.
At the same time, I have come to think that actor is a great type for addressing the 'data race' issues that can arise when using the 'singleton' pattern with class.
Specifically, by using actor, you no longer need to write code like private let lock = DispatchQueue(label: "com.singleton.lock") to prevent data races that you would normally have to deal with when creating a singleton with a class. It reduces the risk of developer mistakes.
import EventKit
actor EKDataStore: Sendable {
static let shared = EKDataStore()
let eventStore: EKEventStore
private init() {
self.eventStore = EKEventStore()
}
}
Of course, since a singleton is an object used globally, it can become harder to manage dependencies over time. There's also the downside of not being able to inject dependencies, which makes testing more difficult.
I still think the singleton pattern is ideal for objects that need to be maintained throughout the entire lifecycle of the app with only one instance. The EKDataStore example I gave is such an object.
I’d love to hear other iOS developers' opinions, and I would appreciate any advice on whether I might be missing something 🙏
Dive into the world of programming languages used for app development.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I wonder if this is correct behavior. I was surprised to get this result when compiling and running the following C code with Apple clang version 14.0.0 (clang-1400.0.29.102) target arm64-apple-darwin21.6.0 on a M1 Pro 12.7.6 with cc -O2 file.c:
#include <stdio.h>
#include <stdlib.h>
unsigned long long factorial(int n)
{
unsigned long long fac = 1;
while (n > 0)
fac *= n;
return fac;
}
int main()
{
return factorial(1);
}
Compiling with -O2 and running this code gives "Trace/BPT trap".
Checking with LLDB:
$ lldb ./a.out
(lldb) target create "./a.out"
Current executable set to '/Users/engelen/Projects/Euler/a.out' (arm64).
(lldb) run
Process 79580 launched: '/Users/engelen/Projects/Euler/a.out' (arm64)
Process 79580 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BREAKPOINT (code=1, subcode=0x100003fb4)
frame #0: 0x0000000100003fb4 a.out`main at 20.c:9:3 [opt]
6 unsigned long long fac = 1;
7 while (n > 0)
8 fac *= n;
-> 9 return fac;
10 }
11
12 int main()
The loop is non-terminating. But a breakpoint trap is triggered at the return statement. The code should just hang in the loop IMO, not trap, because it never updates variable n (a correct factorial function should decrement n). Never seen this before (not since I started wiring C code in the 80s.)
If I change the update *= into += then there is no trap.
Topic:
Programming Languages
SubTopic:
General
I just added a .systemLarge widget to my app, but I can't get Links to work. I want the user to be able to tap one of the four rows in my widget - like the EmojiRangers example - but I can't get it to work.
I watched a Developer video from WWDC20: https://developer.apple.com/videos/play/wwdc2020/10036?time=223
The guy, Izzy, 'simply' embeds an HStack in a Link, and hey presto! It all works. But that doesn't happen for me. There's clearly some code in the background that runs.
I already have .widgetURL working for .systemSmall and .systemMedium widgets, and I don't need to use Links on those two types. Those work by sending a URL to .onOpenURL { incomingURL in ... All good there, no issues.
I've wrapped each row in the large widget in a Link with the URL of something like myappurlscheme://widgetTapped/widgetId (it's the same url as that used in the small and medium widgets). I build & run. I tap a row. It doesn't act as though a row is tappable (it doesn't go slightly transparent), and just opens the app without hitting .onOpenURL or anything else. Nothing in my scene delegate is triggered. Is there a specific delegate method that gets called? Do I need to set up some awful intents?
I'm not using any sort of NavigationStack here; that model doesn't fit my app.
Any ideas? Thanks.
import Foundation
import FirebaseAuth
import GoogleSignIn
import FBSDKLoginKit
class AuthController {
// Assuming these variables exist in your class
var showCustomAlertLoading = false
var signUpResultText = ""
var isSignUpSucces = false
var navigateHome = false
// Google Sign-In
func googleSign() {
guard let presentingVC = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.windows.first?.rootViewController else {
print("No root view controller found.")
return
}
GIDSignIn.sharedInstance.signIn(withPresenting: presentingVC) { authentication, error in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
guard let authentication = authentication else {
print("Authentication is nil")
return
}
guard let idToken = authentication.idToken else {
print("ID Token is missing")
return
}
guard let accessToken = authentication.accessToken else {
print("Access Token is missing")
return
}
let credential = GoogleAuthProvider.credential(withIDToken: idToken.tokenString, accessToken: accessToken.tokenString)
self.showCustomAlertLoading = true
Auth.auth().signIn(with: credential) { authResult, error in
guard let user = authResult?.user, error == nil else {
self.signUpResultText = error?.localizedDescription ?? "Error occurred"
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.showCustomAlertLoading = false
}
return
}
self.signUpResultText = "\(user.email ?? "No email")\nSigned in successfully"
self.isSignUpSucces = true
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.showCustomAlertLoading = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.navigateHome = true
}
}
print("\(user.email ?? "No email") signed in successfully")
}
}
}
// Facebook Sign-In
func signInWithFacebook(presentingViewController: UIViewController, completion: @escaping (Bool, Error?) -> Void) {
let manager = LoginManager()
manager.logIn(permissions: ["public_profile", "email"], from: presentingViewController) { result, error in
if let error = error {
completion(false, error)
return
}
guard let result = result, !result.isCancelled else {
completion(false, NSError(domain: "Facebook Login Error", code: 400, userInfo: nil))
return
}
if let token = result.token {
let credential = FacebookAuthProvider.credential(withAccessToken: token.tokenString)
Auth.auth().signIn(with: credential) { (authResult, error) in
if let error = error {
completion(false, error)
return
}
completion(true, nil)
}
}
}
}
// Email Sign-In
func signInWithEmail(email: String, password: String, completion: @escaping (Bool, Error?) -> Void) {
Auth.auth().signIn(withEmail: email, password: password) { (authResult, error) in
if let error = error {
completion(false, error)
return
}
completion(true, nil)
}
}
}
Topic:
Programming Languages
SubTopic:
Swift
We are Java application developers and we have a question regarding camera access via WebRTC on iPadOS. Specifically, on iPadOS 17.1, we are encountering an issue when trying to access the camera via the WKWebView API in the Chrome browser, where an error occurs and the camera capture fails. Our investigation suggests that device access through the navigator.mediaDevices property via the WKWebView API may not work in Chrome. However, it works as expected in the Safari browser, leading us to wonder if this is a Chrome-specific limitation, or if it's due to an iPadOS setting or specification.
At this point, we are unsure if this issue is related to the WKWebView and WebRTC specifications on iPadOS 17.1, or if there are specific limitations in Chrome. We would appreciate any insights or solutions regarding camera access in iPadOS 17.1 with WKWebView and WebRTC, especially in relation to Chrome.
I can't find the arm_neon.h header file in macOS 15.6.1
This header file defines NEON intrinsics.
Hello,
I am getting an error message "Cannot convert value of type 'URLSessionDataTask' to expected argument type 'Data'" for the last line of this code. Please can you tell me what the problem is? Thank you
struct Item : Codable {
var id: String
var name: String
var country: String
var type: String
var overallrecsit: String
var dlastupd: String
var doverallrecsit: String
}
let url = URL(string:"https://www.TEST_URL.com/api_ios.php")
let json = try? JSONDecoder().decode(Item.self, from: URLSession.shared.dataTask(with: url!))
I'm encountering an issue where certain images are not displaying on some iOS devices, while the same code works perfectly on others. There’s no error or crash — just some images fail to load or display. I've confirmed the image URLs and formats are correct.
Has anyone faced a similar issue or could suggest what might be causing this inconsistent behavior?
Thanks in advance!
Topic:
Programming Languages
SubTopic:
Swift
Hello,
I have a problem with Xcode, in C++ language. When I create a new project, I put my program in a file and click Build. It works correctly and without any problems, but when I enter a second file in the same project and click build, it says build failed. In the log it says, duplicate symbols appear.
Is it ok for an Actor type to have a Publisher as a property to let others observe changes over time? Or use the @Published property wrapper to achieve this?
actor MyActor {
var publisher = PassthroughSubject<Int, Never>()
var data: Int {
didSet {
publisher.send(data)
}
}
...
}
// Usage
var tasks = Set<AnyCancellable>()
let actor = MyActor()
Task {
let publisher = await actor.publisher
publisher.sink { print($0) }.store(in: &tasks)
}
This seems like this should be acceptable. I would expect a Publisher to be thread safe, and as long as the Output is a value type things should be fine.
I have been getting random EXC_BAD_ACCESS errors when using this approach. But turning on the address sanitizer causes these crashes to go away. I know that isn't very specific but I wanted to start by seeing if this type of pattern is ok to do.
In scope of one of our project we've faced an issue with constant crashes when integrating C++ library in Swift code using Swift/C++ interoperability.
Investigating the root causes of the issue we've discovered that with new version of Swift bug was introduced.
Long story short: for strings bigger than 27 symbols memory is feed incorrectly that causes the crashes.
By creating this post I wanted to draw community's attention to the problem and promote it to be solved quicker as for now it is not addressed.
decidePolicyFor delegate method:
import WebKit
@objc extension DocumentationVC
{
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
Being called just alright in swift 5 minimal concurrency.
Raising concurrency to complete with swift 5 or swift 6. Changing the code to avoid warnings:
@preconcurrency import WebKit
@objc extension DocumentationVC
{
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
The delegate method is not being called. Changing back to swift 5 concurrency minimal - it is called.
Looking at WKNavigationDelegate:
WK_SWIFT_UI_ACTOR
@protocol WKNavigationDelegate <NSObject>
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(WK_SWIFT_UI_ACTOR void (^)(WKNavigationActionPolicy))decisionHandler WK_SWIFT_ASYNC(3);
Changing the delegate method to:
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {
And it is called across swift 5 concurrency minimal to complete to swift 6.
I thought, the meaning of @preconcurrency import WebKit was to keep the delegate without @MainActor before the (WKNavigationActionPolicy) still matching regardless the swift concurrency mode?
My point is - this can introduce hidden breaking changes? I didn't see this documented anyhow at: https://www.swift.org/migration/documentation/migrationguide/.
decidePolicyFor is an optional method - so if signature 'mismatches' - there will be no warning on not-implementing the delegate method.
How do we catch or diagnose irregularities like this? Is it something @preconcurrency import WebKit should be ensuring and it is not?
Is this delegate mismatch a bug on swift side or something we should be taking care of while migrating? If it is on us, how do we diagnose these potential mismatches?
Hey team I'm facing an issue where startDate is 1 January 2025 and endDate is 31 March 2025 between this 2 dates is 90 days, but on my code is being taken as 89 days
I've seen the math of the code excludes the first partial day (from midnight to 06:00) on 2025-01-01, which results in 89 full days instead of 90 days.
startDate: 2025-01-01 06:00:00 +0000
endDate: 2025-03-31 06:00:00 +0000
this is my function
func daysBetweenDates() -> Int? {
guard let selectedStartDate = selectedStartDate?.date else { return nil }
guard let selectedEndDate = selectedEndDate?.date else { return 0 }
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.day], from: selectedStartDate, to: selectedEndDate)
return dateComponents.day
}
what I've tried is reset the hours to 0 so it can take the full day and return 90 days
like this
func daysBetweenDates() -> Int? {
guard let selectedStartDate = selectedStartDate?.date else { return nil }
guard let selectedEndDate = selectedEndDate?.date else { return 0 }
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0) ?? .current
let cleanMidNightStartDate = calendar.startOfDay(for: selectedStartDate)
let cleanMidNightEndDate = calendar.startOfDay(for: selectedEndDate.addingTimeInterval(24 * 60 * 60))
let dateComponents = calendar.dateComponents([.day], from: cleanMidNightStartDate, to: cleanMidNightEndDate)
let daysCount = dateComponents.day ?? 0
return daysCount
}
this worked for that date specifically but when I tried to change the date for example
startDate: 18 December 2024.
endDate: 18 March 2025.
between those dates we have 90 days but this function now reads 91.
what I'm looking is a cleaver solution for this problem so I can have the best posible quality code, thanks in advance!
Topic:
Programming Languages
SubTopic:
Swift
Hi all,
Background:
I am working as a library developer and would like to enable Swift C++ interoperability in our library. Our library supports both CocoaPods and SPM.
Question:
I would like to know whether it is possible to avoid breaking changes bring to the library users after enabling Swift C++ interoperability.
In my experiment, all apps and packages depend on the library needs to enable interoperability in Xcode or package manage tools, otherwise the source code cannot be complied.
I am wondering is there any ways to bypass this? For example, is there a way to only enable Swift C++ interoperability only in our libraries?
and yeah, swift vaguely is reminiscent of a programming language I developed, but
I want swift To do
return if (var blah:Int32 == 43){
blah = blah2;
}
your welcome !! thank me on my new accounting job lol =/
basically I want to return conditional statements for a private reason
We are migrating to swift 6 from swift 5 using Xcode 16.2. we are getting below errors in almost each of our source code files :
Call to main actor-isolated initializer 'init(storyboard:bundle:)' in a synchronous non isolated context
Main actor-isolated property 'delegate' can not be mutated from a nonisolated context
Call to main actor-isolated instance method 'register(cell:)' in a synchronous nonisolated context
Call to main actor-isolated instance method 'setup()' in a synchronous nonisolated context
Few questions related to these compile errors.
Some of our functions arguments have default value set but swift 6 does not allow to set any default values. This requires a lot of code changes throughout the project. This would be lot of source code re-write.
Using annotations like @uncheck sendable , @Sendable on the class (Main actor) name, lot of functions within those classes , having inside some code which coming from other classes which also showing main thread issue even we using @uncheck sendable.
There are so many compile errors, we are still seeing other than what we have listed here. Fixing these compile errors throughout our project, would be like a re-write of our whole application, which would take lot of time. In order for us to migrate efficiently, we have few questions where we need your help with. Below are the questions.
Are there any ways we can bypass these errors using any keywords or any other way possible?
Can Swift 5 and Swift 6 co-exist? so, we can slowly migrate over a period of time.
I am currently encountering two deprecated errors in my code. Could someone please identify the issues with the code?
Errors:
'init(coordinateRegion:interactionModes:showsUserLocation:userTrackingMode:annotationItems:annotationContent:)' was deprecated in iOS 17.0: Use Map initializers that take a MapContentBuilder instead.
'MapAnnotation' was deprecated in iOS 17.0: Use Annotation along with Map initializers that take a MapContentBuilder instead.
Code:
// MARK: - Stores Map (Dynamic)
struct StoresMapView: View {
@State private var storeLocations: [StoreLocation] = []
@State private var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: -31.95, longitude: 115.86),
span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)
)
var body: some View {
Map(coordinateRegion: $region, interactionModes: .all, annotationItems: storeLocations) { store in
MapAnnotation(coordinate: CLLocationCoordinate2D(latitude: store.latitude, longitude: store.longitude)) {
VStack(spacing: 4) {
Image(systemName: "leaf.circle.fill")
.font(.title)
.foregroundColor(.green)
Text(store.name)
.font(.caption)
.fixedSize()
}
}
}
.onAppear(perform: loadStoreData)
.navigationTitle("Store Locator")
}
private func loadStoreData() {
guard let url = URL(string: "https://example.com/cop092/StoreLocations.json") else { return }
URLSession.shared.dataTask(with: url) { data, _, _ in
if let data = data, let decoded = try? JSONDecoder().decode([StoreLocation].self, from: data) {
DispatchQueue.main.async {
self.storeLocations = decoded
if let first = decoded.first {
self.region.center = CLLocationCoordinate2D(latitude: first.latitude, longitude: first.longitude)
}
}
}
}.resume()
}
}
I’ve been struggling with this issue for a long time. When I try to archive my app to submit it to the App Store, I encounter two errors:
Linker command failed with exit code 1 (use -v to see invocation)
Linker command failed with exit code 1 (use -v to see invocation)
Topic:
Programming Languages
SubTopic:
Swift
I have the following TaskExecutor code in Swift 6 and is getting the following error:
//Error
Passing closure as a sending parameter risks causing data races between main actor-isolated code and concurrent execution of the closure.
May I know what is the best way to approach this?
This is the default code generated by Xcode when creating a Vision Pro App using Metal as the Immersive Renderer.
Renderer
@MainActor
static func startRenderLoop(_ layerRenderer: LayerRenderer, appModel: AppModel) {
Task(executorPreference: RendererTaskExecutor.shared) { //Error
let renderer = Renderer(layerRenderer, appModel: appModel)
await renderer.startARSession()
await renderer.renderLoop()
}
}
final class RendererTaskExecutor: TaskExecutor {
private let queue = DispatchQueue(label: "RenderThreadQueue", qos: .userInteractive)
func enqueue(_ job: UnownedJob) {
queue.async {
job.runSynchronously(on: self.asUnownedSerialExecutor())
}
}
func asUnownedSerialExecutor() -> UnownedTaskExecutor {
return UnownedTaskExecutor(ordinary: self)
}
static let shared: RendererTaskExecutor = RendererTaskExecutor()
}
Hello
I want to implement customisation to swift argumentparser, Here are following changes want to do it in my cli
changing default footer present in help command output
currently help command output coming like this
OVERVIEW: clisample
USAGE: clisample <subcommand>
OPTIONS:
--version show the version.
-h, --help show the help.
SUBCOMMANDS:
logs (default) Export logs for clisample processes.
See 'clisample --help' for more information.'
so instead of
See 'clisample --help' for more information.'
I want my own string
For more details, run 'clisample help <subcommand>'
customise error string getting from validation error
Error: Missing value for '-t <time>'
Help: -t <time> Time window (e.g. 10h, 30m, 2d).
Usage: clisample logs --time <time>
See 'clisample logs --help' for more information.
so I want error output with example and customised footer, like this
Error: Missing value for '-t <time>'
Help: -t <time> Time window (e.g. 10h, 30m, 2d).
Usage: clisample logs --time <time>
Example: clisample logs -t 5m
For more details, run 'clisample help <subcommand>'
Is this changes possible from anyway?