I have this code:
var eventIn = kevent(ident: UInt(self.socket),
filter: Int16(EVFILT_WRITE),
flags: UInt16((EV_ADD | EV_ENABLE)),
fflags: 0,
data: 0,
udata: nil
)
I looked at it and thought why do I have those extra parentheses? So I changed it to
var eventIn = kevent(ident: UInt(self.socket),
filter: Int16(EVFILT_WRITE),
flags: UInt16(EV_ADD | EV_ENABLE), // changed line!
fflags: 0,
data: 0,
udata: nil
)
and then kevent gave me EBADF.
Does this make sense to anyone?
Swift
RSS for tagSwift is a powerful and intuitive programming language for Apple platforms and beyond.
Posts under Swift tag
200 Posts
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hi the below array and code to output a list item works fine:
var quotes = [
[
"quote": "I live you the more ...",
"order": "1"
],
[
"quote": "There is nothing permanent ...",
"order": "2"
],
[
"quote": "You cannot shake hands ...",
"order": "3"
],
[
"quote": "Lord, make me an instrument...",
"order": "4"
]
]
cell.textLabel?.text = quotes[indexPath.row]["quote"]
However if I change the "order" values to be numbers rather than text like below then for the above line I get an error message in Xcode "No exact matches in call to subscript". Please could someone tell me how to make it work with the numbers stored as numbers? (I'm wondering if creating an any array type and using the .text function has caused a conflict but I can't find how to resolve)
[
"quote": "I live you the more ...",
"order": 1
],
[
"quote": "There is nothing permanent ...",
"order": 2
],
[
"quote": "You cannot shake hands ...",
"order": 3
],
[
"quote": "Lord, make me an instrument...",
"order": 4
]
]
Thank you for any pointers :-)
I used Swift Playground to develop application in Mac OS. Also using ZStack I used limited area in full page (using .frame(width: $, height: $)). However using command + R or clicking start button to see preview .app, while non resizing application my ZStack show as cutted. Please tell me how to set preview .app frame size as width, height... The buttom code is ContentView.swift code.
@main
struct ContentView: App {
init() {
MyFont.registerFonts()
}
// @StateObject private var audioPlayer = AudioPlayer()
var body: some Scene {
WindowGroup {
NavigationStack {
StartMenuView()
.frame(minWidth: 594, maxWidth: 594,
minHeight: 1142, maxHeight: 1142)
.preferredColorScheme(.dark) // Dark Mod
.statusBar(hidden: true) // Hidden Status Bar
.edgesIgnoringSafeArea(.all) // Ignoring Safe Area
}
}
.windowResizability(.contentSize)
}
}
Thank you for reading.


Topic:
Developer Tools & Services
SubTopic:
Swift Playground
Tags:
Swift
App Review
Swift Playground
Is there a way to create a Date constant from year, month and day? The only constructors that show up are .now and those based on some timeInterval. I'm trying to initialize some test data with known dates.
I am using Xcode 15 and working on a localised app. I use the new String Catalogs feature which works great for my app. In my app I created some local package like Apple has done it in the Backyard Birds example. However the translations I did in the package's String Catalog won’t be used in the app. What am I doing wrong?
Hello folks,
I'd like to report a bug in Swift Playground to Apple official dev team, it's in "Learn to Code 2" - "Seeking Seven Gems".
The puzzle map can't be loaded, please check the following screenshot,
My system environment:
MacOS 15.3
Swift 6.0.3 (swift-driver version: 1.115.1 Apple Swift version 6.0.3 (swiftlang-6.0.3.1.10 clang-1600.0.30.1))
Swift Playground 4.6.2
Xcode 16.2
Hardware: MacBook Pro/M2 Pro/32G
Topic:
Developer Tools & Services
SubTopic:
Swift Playground
Tags:
Developer Tools
Swift Student Challenge
Swift
I am able to setup and schedule a background refresh task as well as manually trigger it via Xcode and the simulator tied to my iPhone 11 Pro test phone using the e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier: However, it won't execute on the app on it's own. And yes, the pinfo.list entries are correct and match!
I know the scheduler is not exact on timing but it's just not executing on its own. Since I can trigger manually it I'm pretty sure the code is good but I must be missing something.
I created an observable object for this code and the relevant parts look like this:
class BackgroundTaskHandler: ObservableObject {
static let shared = BackgroundTaskHandler()
var taskState: BackgroundTaskState = .idle
let backgroundAppRefreshTask = "com.opexnetworks.templateapp.shell.V1.appRefreshTask"
func registerBackgroundTask() {
BGTaskScheduler.shared.register(forTaskWithIdentifier: backgroundAppRefreshTask, using: nil) { task in
self.handleAppRefresh(task: task as! BGAppRefreshTask)
}
self.updateTaskState(to: .idle, logMessage: "✅ Background app refresh task '\(backgroundAppRefreshTask)' registered.")
BGTaskScheduler.shared.register(forTaskWithIdentifier: backgroundTaskIdentifier, using: nil) { task in
self.handleProcessingTask(task: task as! BGProcessingTask)
}
self.updateTaskState(to: .idle, logMessage: "✅ Background task identifier '\(backgroundTaskIdentifier)' registered.")
}
// Handle the app refresh task
private func handleAppRefresh(task: BGAppRefreshTask) {
self.updateTaskState(to: .running, logMessage: "🔥 app refresh task is now running.")
PostNotification.sendNotification(title: "Task Running", body: "App refresh task is now running.")
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
let operation = BlockOperation {
self.doSomeShortTaskWork()
}
task.expirationHandler = {
self.updateTaskState(to: .expired, logMessage: "💀 App refresh task expired before completion.")
PostNotification.sendNotification(title: "Task Expired", body: "App refresh task expired before completion \(self.formattedDate(Date())).")
operation.cancel()
}
operation.completionBlock = {
if !operation.isCancelled {
self.taskState = .completed
}
task.setTaskCompleted(success: !operation.isCancelled)
let completionDate = Date()
UserDefaults.standard.set(completionDate, forKey: "LastBackgroundTaskCompletionDate")
self.updateTaskState(to: .completed, logMessage: "🏁 App refresh task completed at \(self.formattedDate(completionDate)).")
PostNotification.sendNotification(title: "Task Completed", body: "App refresh task completed at: \(completionDate)")
self.scheduleAppRefresh() // Schedule the next one
}
queue.addOperation(operation)
}
func scheduleAppRefresh() {
// Check for any pending task requests
BGTaskScheduler.shared.getPendingTaskRequests { taskRequests in
let refreshTaskIdentifier = self.backgroundAppRefreshTask
let refreshTaskAlreadyScheduled = taskRequests.contains { $0.identifier == refreshTaskIdentifier }
if refreshTaskAlreadyScheduled {
self.updateTaskState(to: .pending, logMessage: "⚠️ App refresh task '\(refreshTaskIdentifier)' is already pending.")
// Iterate over pending requests to get details
for taskRequest in taskRequests where taskRequest.identifier == refreshTaskIdentifier {
let earliestBeginDate: String
if let date = taskRequest.earliestBeginDate {
earliestBeginDate = self.formattedDate(date)
} else {
earliestBeginDate = "never"
}
self.updateTaskState(to: .pending, logMessage: "⚠️ Pending Task: \(taskRequest.identifier), Earliest Begin Date: \(earliestBeginDate)")
}
// Optionally, show a warning message to the user in your app
PostNotification.sendNotification(title: "Pending Tasks", body: "App refresh task is already pending. Task scheduling cancelled.")
return
} else {
// No pending app refresh task, so schedule a new one
let request = BGAppRefreshTaskRequest(identifier: refreshTaskIdentifier)
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // Earliest in 15 minutes
do {
try BGTaskScheduler.shared.submit(request)
self.taskState = .scheduled
self.updateTaskState(to: .scheduled, logMessage: "✅ App refresh task '\(refreshTaskIdentifier)' successfully scheduled for about 15 minutes later.")
PostNotification.sendNotification(title: "Task Scheduled", body: "App refresh task has been scheduled to run in about 15 minutes.")
} catch {
print("Could not schedule app refresh: \(error)")
self.taskState = .failed
self.updateTaskState(to: .failed, logMessage: "❌ Failed to schedule app refresh task.")
}
}
}
}
// Short task work simulation
private func doSomeShortTaskWork() {
print("Doing some short task work...")
// Simulate a short background task (e.g., fetching new data from server)
sleep(5)
print("Short task work completed.")
}
In my AppDelegate I trigger the registerBackground task in the didFinishLaunchingWithOptions here:
BackgroundTaskHandler.shared.registerBackgroundTask()
And I scheduled it here in the launch view under a task when visible:
.task {
BackgroundTaskHandler.shared.scheduleAppRefresh()
}
I've also tried the last in the AppDelegate after registering. either way the task schedules but never executes.
I found some snapshot API in developer documents, like blows:
RealityKit / Views and attachments / ARView / /snapshot(saveToHDR:completion:)
SceneKit / SCNView / snapshot()
Is there a similar API in visionOS?and if not, how can I implement snapshot for realityview and usdz?
Hi everyone,
I believe this should be a simple and expected default behavior in a real-world app, but I’m unable to make it work:
1. I have a View (a screen/page in this case) that calls an endpoint using async/await.
2. If the endpoint hasn’t finished, but I navigate forward to a DetailView, I want the endpoint to continue fetching data (i.e., inside the @StateObject ViewModel that the View owns). This way, when I go back, the View will have refreshed with the fetched data once it completes.
3. If the endpoint hasn’t finished and I navigate back to the previous screen, I want it to be canceled, and the @StateObject ViewModel should be deinitialized.
I can achieve 1 and 3 using the .task modifier, since it automatically cancels the asynchronous task when the view disappears:
view
.task { await vm.getData() }
I can achieve 1 and 2 using a structured Task in the View (or in the ViewModel, its the same behavior), for example:
.onFirstAppearOnly {
Task { away vm.getData() }
}
onFirstAppearOnly is a custom modifier that I have for calling onAppear only once in view lifecycle. Just to clarify, dont think that part is important for the purpose of the example
But the question is: How can I achieve all three behaviors? Is this really such an unusual requirement?
My minimum deployment target is iOS 15, and I’m using NavigationView + NavigationLink. However, I have also tried using NavigationStack + NavigationPath and still couldn’t get it to work.
Any help would be much appreciated.
Thank you, folks!
Hello!
I'm trying to set a UiRefreshControl.tintColor:
.onAppear {
UIRefreshControl.appearance().tintColor = UIColor.systemBlue
}
But instead of
I get
The color in the second picture is a high contrast version of the first one. I can't understand why it works this way.
I also tried the following.
UIRefreshControl.appearance().tintColor = UIColor(red: 0, green: 0.478, blue: 1, alpha: 1) // doesn't work
UIRefreshControl.appearance().tintColor = UIColor(named: "RefreshControlColor") // doesn't work, here set "High contrast" on and indicated Universal.systemBlueColor
Perhaps I missed something?
Hi guys, I’m making a simple note taking app and I want to support markdown functionality. I have tried to find libraries and many other GitHub repos but some of them are slow and some of them are very hard to implement and not very customizable.
In WWDC 22 apple also made a markdown to html document app and I also looked at that code and it was awesome. It was fast and reliable (Apple btw).
But the only problem I am facing is that the markdown text is on the left side and the output format is on the right in the form of html. I don’t want that I want both in the same line. In bear notes and things 3 you can write in markdown and you can see that it is converting in the same line. I have also attached example videos. So, I have markdown parser by apple but the only thing in the way is that it is converting it into a html document. Please help me with this. Also please look into the things 3 video they have also completely customized the text attributes selection menu. By default with UITextView we can only enable text attributes and it shows like this.
By clicking more we get the complete formatting menu but not the slider menu which is more convenient. Please also help me this. I don’t know if I can provide apple file but it is from wwdc 22 supporting desktop class interaction
we have three problem when using the push notification on Live Activity.
1. What is the specific callback strategy for the activityUpdates property in ActivityKit?
We found that in actual user scenarios, there is a probability that we may not receive callbacks. From the community experience, there are some resource optimization strategies that do not perform callbacks. From this perspective, the explanation is kind of vague. Is there any clear feedback to understand why callbacks are performed/not performed?
2.what is the specific description of the wake-up strategy, when background app receive Live Activity offline start Push?
From community experience, we can see that the system may wake up for a duration of 0-30s due to resource optimization strategies, or not wake up/not deal with it. Is there an official description of the wake-up strategy? or we also have to follow this description:
Wake up of apps using content-available pushes are heavily throttled. You can expect 1-2 wakeup per hour as a best case scenario in the hands of your users. so this cannot be assumed to be a reliable wake-up on demand mechanism for an app.
3 How can we determine user have selected (allow or always allow) of the Live Activity permission?
When we use real-time activity offline push, there are two system prompts in iOS:
the first prompt : allow and disallow real-time activity
the second prompt : always allow and disallow
Is there an interface that can directly determine which permission the user has chosen (allow/always allow)? (By the way, we can get disallow status).
At present, we haven't seen any interface in the official documentation/interface that can determine (allow/always allow). The difference here will affect the generation of Update Token. Without Update Token, we can not update our activity instance.
I'm unable to rename my Swift Playground or add/change the app icon when I imported a package dependency after upgraded my Swift Playgrounds App to the newest version. Every time I tried to do that, the whole project will be destroyed and showed error message below.
I wonder if anyone have same experience with me or someone can tell me the solution, it terrifies me and I'm worried that I'll be unable to submit my project on time because of that.
Hi!
I get personal recommendations MusicItemCollection using this code:
func getRecommendations() async throws -> MusicItemCollection<MusicPersonalRecommendation> {
let request = MusicPersonalRecommendationsRequest()
let response = try await request.response()
let recommendations = response.recommendations
return recommendations
}
However, all recommendations contain no more than 12 MusicItem's, while the Music.app application provides much more for some recommendations, for example, for the You recently listened recommendation, the Music.app application displays 40 items. Each recommendation has an items property that contains a collection of musical items MusicItemCollection<MusicPersonalRecommendation.Item>, the hasNextBatch property for these collections is always false. I expected that for some collections loading of new items would be available. Please tell me if I'm doing something wrong or is this a MusicKit bug?
Thank you!
The App has the ability to use WebKit and display web pages and the ability to add phone numbers to CallDirectory at specific timing.
In this App, when the App is launched or when the Add Contact button on the web page is pressed,
CallDirectoryExtention is reloaded from the host app (WebKit-viewController), the phone number is retrieved from the server, and the entry is updated.
I would like to add a process to remove the already added phone number entry when a specific value is retrieved from the application server.
The specific process we wish to implement is as follows.
Step 1: Use URLsession to retrieve values from the application server. (ViewController)
Step 2: If the value is a specific value, call a Function that deletes the CallDirectoryExtention entry. (ViewController)
Step 3: Delete all entries for the registered phone numbers.
However, I am aware that I have to use reloadExtension() to call the CallDirectoryExtention process from ViewController on Step2.
if I do so, CallDirectoryHandler.beginRequest() will be processed, and I am wondering if it is not possible to execute only the Function that deletes the entry.
Is there a way to run only the Function that deletes the CallDirectoryExtention entry from the host app(viewController)?
Fatal Error in Swift Playground
Description
I'm experiencing a catastrophic error when importing Package Dependency in any Swift Playgrounds that has icon or name that caused the whole Playground won't work anymore with error messages below.
I'm current running macOS Sequoia 15.3 (24D60) and Swift Playgrounds 4.6.1. They're all up-to-date.
Reproduction
Open Swift Playgrounds and and create a new project.
Import a package dependency
https://github.com/simibac/ConfettiSwiftUI.git
Rename the project and add an icon
Then you should able the reproduce the problem. I strongly believed that this is a serious bug.
You'll find that Assets in the left column are disappeared and appeared Assets.xcassets, you're unable to reveal the Dependency in the column like the reference picture above. The whole Playground is destroyed now and unable to work anymore.
Topic:
Developer Tools & Services
SubTopic:
Swift Playground
Tags:
Swift Packages
Swift
Swift Playground
I am trying to use AVAudioEngine for recording and playing for a voice chat kind of app, but when the speaker plays any audio while recording, the recording take the speaker audio as input. I want to filter that out. Are there any suggestions for the swift code
I am developing an iOS application that supports screen mirroring to Google TV (or Chromecast with Google TV). My goal is to mirror the iPhone/iPad screen in real time to a Google TV device.
What I Have Tried So Far
I have explored multiple approaches but haven't found a direct way to achieve low-latency screen mirroring. Here are some of my findings:
Google Cast SDK:
Google Cast SDK is primarily designed for casting media (videos, images, audio) rather than real-time mirroring. It supports custom receiver applications, but there are no direct APIs for full screen mirroring. Casting a recorded video is possible, but it introduces latency and is not real-time.
ReplayKit for Screen Capture:
RPScreenRecorder.shared().startCapture(handler: ...) allows capturing the iPhone screen as a video stream. However, sending this stream to Google TV in real time is a challenge. I could potentially encode the video as HLS and stream it, but the delay is significant.
RTSP/UDP Streaming:
Some third-party libraries support RTSP/UDP streaming for real-time screen sharing. Google TV does not natively support RTSP, making this approach difficult.
My Questions:
Is it possible to achieve real-time screen mirroring on Google TV using Google Cast SDK? Does Google TV support WebRTC or any low-latency streaming protocol that can be used from iOS? Are there any alternative approaches to mirror an iOS screen to Google TV with minimal latency? I would appreciate any guidance, code examples, or references to relevant documentation.
I am interested in participating in the Swift Student Challenge. My application contains a significant amount of augmented reality (AR) content, necessitating access to the camera. It is evident that if the reviewer utilizes a simulator or operates on a Mac, they will not be able to experience the AR function. Therefore, the AR function in the camera experience application must be utilized to access a real iPad.
However, it is mentioned in https://developer.apple.com/forums/thread/773530 that the plan is to evaluate Xcode app playgrounds within the simulator. Additionally, I observed the statement “Note: Xcode app playgrounds are executed in Simulator” on the submission page. Consequently, it is clear that the reviewers are limited to using a simulator or running my application on a Mac.
In light of this, I am seeking guidance on how to enable the reviewer to utilize a real iPad to access the AR function in the camera experience application. Alternatively, I may need to reconsider my strategy and discontinue utilizing AR.
Topic:
Community
SubTopic:
Swift Student Challenge
Tags:
Swift Student Challenge
Swift
Swift Playground
Swans Quest
I am currently developing a custom-protocol VPN application for iOS using PacketTunnelProvider. I have also integrated an HTTP proxy service, which is launched via a dylib.
The overall flow is as follows:
App -> VPN TUN -> Local HTTP Proxy -> External Network
I have a question:
I am capturing all traffic, and normally, requests sent out by the HTTP proxy are also captured again by the VPN. However, when I send requests using createUdpSession in my code, they are not being captured by the virtual interface (TUN).
What could be the reason for this?
override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) {
let tunnelNetworkSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "192.168.18.0")
tunnelNetworkSettings.mtu=1400
let ipv4Settings = NEIPv4Settings(addresses: ["192.169.10.10"], subnetMasks: ["255.255.255.0"])
ipv4Settings.includedRoutes=[NEIPv4Route.default()]
ipv4Settings.excludedRoutes = [NEIPv4Route(destinationAddress: "10.0.0.0", subnetMask: "255.0.0.0"),
NEIPv4Route(destinationAddress: "172.16.0.0", subnetMask: "255.240.0.0"),
NEIPv4Route(destinationAddress: "192.168.0.0", subnetMask: "255.255.0.0"),
NEIPv4Route(destinationAddress:"127.0.0.0", subnetMask: "255.0.0.0"),
]
tunnelNetworkSettings.ipv4Settings = ipv4Settings
// Configure proxy settings
let proxySettings = NEProxySettings()
proxySettings.httpEnabled = true
proxySettings.httpServer = NEProxyServer(address: "127.0.0.1", port: 7890)
proxySettings.httpsEnabled = true
proxySettings.httpsServer = NEProxyServer(address: "127.0.0.1", port: 7890)
proxySettings.excludeSimpleHostnames = true
proxySettings.exceptionList=["localhost","127.0.0.1"]
tunnelNetworkSettings.proxySettings = proxySettings
setTunnelNetworkSettings(tunnelNetworkSettings) { [weak self] error in
if error != nil {
completionHandler(error)
return
}
completionHandler(nil)
let stack = TUNInterface(packetFlow: self!.packetFlow)
RawScoketFactory.TunnelProvider=self
stack.register(stack: UDPDirectStack())
stack.register(stack: TCPDirectStack())
stack.start()
}
}
NWUdpSession.swift
//
// NWUDPSocket.swift
// supervpn
//
// Created by TobbyQuinn on 2025/2/3.
//
import Foundation
import NetworkExtension
import CocoaLumberjack
public protocol NWUDPSocketDelegate: AnyObject{
func didReceive(data:Data,from:NWUDPSocket)
func didCancel(socket:NWUDPSocket)
}
public class NWUDPSocket:NSObject{
private let session:NWUDPSession
private let timeout:Int
private var pendingWriteData: [Data] = []
private var writing = false
private let queue:DispatchQueue=QueueFactory.getQueue()
public weak var delegate:NWUDPSocketDelegate?
public init?(host:String,port:UInt16,timeout:Int=Opt.UDPSocketActiveTimeout){
guard let udpSession = RawScoketFactory.TunnelProvider?.createUDPSession(to: NWHostEndpoint(hostname: host, port: "\(port)"), from: nil) else{
return nil
}
session = udpSession
self.timeout=timeout
super.init()
session.addObserver(self, forKeyPath: #keyPath(NWUDPSession.state),options: [.new], context: nil)
session.setReadHandler({ dataArray, error in
self.queueCall{
guard error == nil, let dataArray = dataArray else {
print("Error when reading from remote server or connection reset")
return
}
for data in dataArray{
self.delegate?.didReceive(data: data, from: self)
}
}
}, maxDatagrams: 32)
}
/**
Send data to remote.
- parameter data: The data to send.
*/
public func write(data: Data) {
pendingWriteData.append(data)
checkWrite()
}
public func disconnect() {
session.cancel()
}
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard keyPath == "state" else {
return
}
switch session.state {
case .cancelled:
queueCall {
self.delegate?.didCancel(socket: self)
}
case .ready:
checkWrite()
default:
break
}
}
private func checkWrite() {
guard session.state == .ready else {
return
}
guard !writing else {
return
}
guard pendingWriteData.count > 0 else {
return
}
writing = true
session.writeMultipleDatagrams(self.pendingWriteData) {_ in
self.queueCall {
self.writing = false
self.checkWrite()
}
}
self.pendingWriteData.removeAll(keepingCapacity: true)
}
private func queueCall(block:@escaping ()->Void){
queue.async {
block()
}
}
deinit{
session.removeObserver(self, forKeyPath: #keyPath(NWUDPSession.state))
}
}