Hi,
class AppDelegate: NSObject, UIApplicationDelegate, ObservableObject {
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
print("AppDelegate: application(willFinishLaunchingWithOptions)")
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
print("AppDelegate: application(open:options)")
return true
}
}
use scheme simpletest://what in Safari can bring the app from background to foreground, but application(open:options) is not invoked.
application(willFinishLaunchingWithOptions) is always called.
The Swift projct is clean and only with XCode generated demo code except the AppDelegate.
Can anybody please help?
Dive into the world of programming languages used for app development.
Post
Replies
Boosts
Views
Activity
I have an exception handling frame for an Xcode application in macOS, which contains Cpp and Swift code. I am using the Unix signals frame for handling exceptions using sigaction. My sigaction signal handler get invoked when there is a swift or Cpp exception. However for some exceptions like SIGSEGV, the signal handler gets called repeatedly. To handle this I am using the SA_RESETHAND flag so that the handler gets invoked only once, and then the default action for the signal take over to terminate the process.
This approach works well when an exception occurs due to Cpp code, however when it occurs due to Swift code, the signal handler still gets invoked repeatedly. Can someone explain why is this happening and What is the solution to this?
Dear all,
I'm new in coding, for maybe the fifth time :), and I hope I find the right words.
Right now I'm prototyping a 3D game with scenekit for IOS devices. At the moment the prototyp of the MainScene.scn (the first game scene) is ready. The 3D objects are located in the assetcatalog, and the game behavior with object movements, gyro data, 3D Text and so on, is codet in the GameViewController.swift.
Now I’m at a point where I think I can do many things wrong, at the cost of days, weeks or months of work, to reconstruct my app, afterwards.
So I want to understand, what's the „sexiest“ way to structure my project Scenes, Views, Controller, etc.
Simplified, my game will have a user interface to store the name, change gameplay setting and so on, and it will have multiple 3D scenes where the game takes place.
At first I thought, it would be a good idea to arrange multiple scenes, all controlled by the GameViewController, due to not having to duplify recurring methods or so. But as I thought of, I saw a GameViewController file bigger and bigger and I had the fear to more and more loosing the focus the more scenes I added.
The thought of multiple Controller for each or a fiew Scenes are not as „****“ too, because by changes on a recurring method, I maybe have to change it for every Controller.
I then thought of instancing the GameViewController but in no case I had the feeling „that’s the way to go“.
So long things short: How would you arrange a game project like this?
Thank you in advance,
Ray
I am having a problem with named captures when build with a Regex Builder.
The following code is a simplistic example of the problem that works using an "ordinary" Regex. but when the same regular regex is created with a Regex Builder, it works when using group numbers, but it raises the following typing problem when using capture names (last lines)
Cannot infer type of closure parameter 'm' without a type annotation
// named captures and use with a Regex string to twiggle every alternate chars
let pat = /(?P<a>.)(?P<b>.)/
"abcdef".replacing(pat,with:{m in "\(m.b)\(m.a)"})
// the same Regex but using a Regex Builder
let a = Reference(Substring.self)
let b = Reference(Substring.self)
let patRB = Regex {
Capture(as: a) {.any}
Capture(as: b) {.any}
}
// OK when using capture group numbers
"abcdef".replacing(patRB,with:{m in "\(m.2)\(m.1)"})
// compile error when using group names
"abcdef".replacing(patRB,with:{m in "\(m.b)\(m.a)"})
The following shows the output strings in a Playground
Any hints on what is wrong or on the correct way to add typing information to the closure.
Thanks
I am trying to create a generic structure in my project and I am facing an issue where I get the error "Type 'any B' cannot conform to 'A'", where protocol B is derived from protocol A.
I don't understand why such a structure is problematic and I would really appreciate any insight or alternative solution for this issue I am having.
Issue:
I have a general base protocol-class pair like the following.
protocol A { }
class AClass<T: A> { }
To give an example of my use case, protocol A can be PresenterLogic where AClass is BaseInteractor.
I have a second protocol-class pair which I want to specialize according to its use case.
protocol B: A { }
class BClass: AClass<B> { } // Here, I get "Type 'any B' cannot conform to 'A'"
For example, protocol B being MyPresenterLogic and class BClass being MyInteractor.
Specific Use-Case:
To give a more specific use case, I am trying to build a VIP structure such as the following.
// Base VIP (Ex: Interactor)
protocol PresenterLogic {
}
class Interactor<PL: PresenterLogic>, BusinessLogic {
var presenter: PL?
}
// VIP for Specific Screen (Ex: Interactor)
protocol MyPresenterLogic: PresenterLogic {
}
class MyInteractor: Interactor<MyPresenterLogic> {
// I don't want to declare a second `myPresenter: MyPresenterLogic` here
}
I don't want to declare another presenter instance in MyInteractor, (such as myPresenter: MyPresenterLogic. I want to be able to use the same presenter instance to be inferred to have the sub-protocol type.
That is why I want to use generic classes, but I am stuck. I am searching if this is supported. Any insight is appreciated. Thank you.
persist images even after the app is uninstalled, if we reinstall the app can we display same images in app? but our app not use any cloud or server. Thanks in advance.
I have verified NSExtensionPrincipalClass, appGroup. We are using authentication with File Provider UI but when I tried to debug the extension, AppDelegate is getting called instead if initialising the File Provider extension class with iOS 17.4 but it's working well with 17.2
Wanted to reach out for some assistance with troublshooting my watch app not detecting collision, I have set up a few breakpoints and determined that it is not running the game over struct even if it had detected the collision, I have also tried to generate a log file when a collision is detected and that does not work either. I have considered that the objects may not be on the same layer so they are now in the same zstack.
I am trying to include custom symbol resources in a swift package for use in other projects. I have read the documentation here:
https://developer.apple.com/documentation/xcode/bundling-resources-with-a-swift-package
However there is no example code and I have created a very simple project to try and get this working but it does not.
.target(
name: "TestLibrary",
resources: [.process("Resources/Media.xcassets")]
),
This is in the Package.swift file and the path relative to the Package.swift file is Sources/TestLibrary/Resources/Media.xcassets.
There's a GitHub project with an example custom SF Symbol SVG (but this may not be available in the future): https://github.com/kudit/TestLibrary
Including this as a package in a blank Swift Playgrounds App project and just importing the TestLibrary and including TestImageView() in the ContentView technically works (it shows the system full star image, but none of the ways of rendering the test symbol as recommended works. It does work for a few of the options in the #Preview when viewing the project in Xcode.
Anyone have any suggestions or know how to get the resources to be accessible from outside the module? I have tried both the .copy( option as well as the .process( option and neither seem to work.
The following Swift UIKit code produces the warning "Cannot access property 'authController' with a non-sendable type 'AuthController' from non-isolated deinit; this is an error in Swift 6":
import UIKit
class AuthFormNavC: UINavigationController {
let authController: AuthController
init(authController: AuthController) {
self.authController = authController
super.init(rootViewController: ConsentVC())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
authController.signInAnonymouslyIfNecessary()
}
}
Swift 5.10, Xcode 15.3 with complete strict concurrency checking.
What is the workaround?
Please don't ask me why I'm doing what I'm doing or anything unrelated to the question.
If you're wondering why I want to call authController.signInAnonymouslyIfNecessary() when the navigation controller is denitialized, my goal is to call it when the navigation controller is dismissed (or popped), and I think that the deinitializer of a view controller is the only method that is called if and only if the view controller is being dismissed (or popped) in my case. I tried observing variables like isViewLoaded in the past using KVO but I couldn't get it to work passing any combination of options in observe(_:options:changeHandler:).
I am trying to create an app for a custom Now Playing UI. How can I grab the following:
Song Name
Album Name
Artist Name
Album Art
so, my app needs to find the dominant palette and the position in the image of the k-most dominant colors. I followed the very useful sample project from the vImage documentation
https://developer.apple.com/documentation/accelerate/bnns/calculating_the_dominant_colors_in_an_image
and the algorithm works fine although I can't wrap my head around how should I go on about and linking said colors with a point in the image. Since the algorithm works by filling storages first, I tried also filling an array of CGPoints called LocationStorage and working with that
//filling the array
for i in 0...width {
for j in 0...height {
locationStorage.append(
CGPoint(x: i, y: j))
}
.
.
.
//working with the array
let randomIndex = Int.random(in: 0 ..< width * height)
centroids.append(Centroid(red: redStorage[randomIndex],
green: greenStorage[randomIndex],
blue: blueStorage[randomIndex],
position: locationStorage[randomIndex]))
}
struct Centroid {
/// The red channel value.
var red: Float
/// The green channel value.
var green: Float
/// The blue channel value.
var blue: Float
/// The number of pixels assigned to this cluster center.
var pixelCount: Int = 0
var position: CGPoint = CGPointZero
init(red: Float, green: Float, blue: Float, position: CGPoint) {
self.red = red
self.green = green
self.blue = blue
self.position = position
}
}
although it's not accurate.
I also tried force trying every pixel in the image to get as close to each color but I think it's too slow.
What do you think my approach should be?
Let me know if you need additional info
Please be kind I'm learning Swift.
Hello, I have started using the DragRotationModifier from the Hello World demo project by Apple. I have run into a bug that I can't seem to figure out for the life of me where everything seems to work fine for about 3-5 seconds of moment before it starts rapidly spinning for some reason. I took a video but it looks like I am unable to post any link to outside sources like imgur or youtube so ill try to describe it as best I can:
Basically I can spin the sample USDZ Nike Airforce from the Apple sample objects perfectly, but after about 3-5 seconds it seems to rapidly snap between different other rotations and the rotation where the "cursor" is. A couple of additional notes, this only happens when the finger pinch/drag gesture is interacting with the object and this spin only affects the Yaw rotation axis of the object.
I created an "Imported Model Entity" wrapper that does some additional stuff when importing a USDZ model similar to the Hello World demo. Then, within a RealityView I create an instance of this ImportedModelEntity and attach the Drag Rotation Modifier to the view like this:
RealityView { content in
let modelEntity = await ImportedModelEntity(configuration: modelViewModel.modelConfiguration)
content.add(modelEntity)
self.modelEntity = modelEntity
content.add(BoundsVisualizer(bounds: [0.6, 0.6, 0.6]))
//Scale object to half of the size of Volume view
let bounds = content.convert(geometry.frame(in: .local), from: .local, to: content)
let minExtent = bounds.extents.min()
modelViewModel.modelConfiguration.scale = minExtent
}
update: { content in
modelEntity?.update(configuration: modelViewModel.modelConfiguration)
}
.if(modelEntity != nil) { view in
view.dragRotation(
pitchLimit: .degrees(90),
targetEntity: modelEntity!,
sensitivity: 10,
axRotateClockwise: axRotateClockwise,
axRotateCounterClockwise: axRotateCounterClockwise)
}
For reference here is my ImportedModelEntity:
import Foundation
import RealityKit
class ImportedModelEntity: Entity {
// MARK: - Sub-entities
private var model: ModelEntity = ModelEntity()
private let rotator = Entity()
// MARK: - Internal state
// MARK: - Initializers
@MainActor required init() {
super.init()
}
init(
configuration: Configuration
) async {
super.init()
if(configuration.modelURL == nil) {
fatalError("Provided modelURL is NOT valid!!")
}
//Load the custom model on main thread
// DispatchQueue.main.async {
do {
let input: ModelEntity? = try await ModelEntity(contentsOf: configuration.modelURL!)
guard let model = input else { return }
self.model = model
// let material = SimpleMaterial(color: .green, isMetallic: false)
// model.model?.materials = [material]
//Add input components
model.components.set(InputTargetComponent())
model.generateCollisionShapes(recursive: true)
// Add Hover Effect
model.components.set(HoverEffectComponent())
//self.model.components.set(GroundingShadowComponent(castsShadow: configuration.castsShadow))
// Add Rotator
self.addChild(rotator)
// Add Model to rotator
rotator.addChild(model)
} catch is CancellationError {
// The entity initializer can throw this error if an enclosing
// RealityView disappears before the model loads. Exit gracefully.
return
} catch let error {
print("Failed to load model: \(error)")
}
// }
update(configuration: configuration)
}
//MARK: - Update Handlers
func update(
configuration: Configuration)
{
rotator.orientation = configuration.rotation
move(to: Transform(
scale: SIMD3(repeating: configuration.scale), rotation: orientation, translation: configuration.position), relativeTo: parent)
}
}
Any help is greatly appreciated!
Hi,
I have an issue that I don't understand, and I need help. I am using Pipe() in Swift, and I found that if I create more than 2560 (more or less) pipes, I cannot create more. The call fails with Too many open files, even though I closed all the files associated with the pipes.
This is a minimal code to reproduce the issue:
for i in 0...1278 {
NSLog("Testing: \(i)")
let stdin_pipe = Pipe()
let stdin_file = fdopen(stdin_pipe.fileHandleForReading.fileDescriptor, "r")
var stdout_pipe = Pipe()
var stdout_file = fdopen(stdout_pipe.fileHandleForWriting.fileDescriptor, "w")
if (stdout_file == nil) {
let errorString = String(cString: strerror(errno))
NSLog("Could not create an output stream. Error: \(errorString)")
}
do {
// I'm really trying to close everything (but it doesn't matter):
close(stdout_pipe.fileHandleForWriting.fileDescriptor)
close(stdin_pipe.fileHandleForReading.fileDescriptor)
try stdout_pipe.fileHandleForWriting.close()
try stdin_pipe.fileHandleForReading.close()
try stdout_pipe.fileHandleForReading.close()
try stdin_pipe.fileHandleForWriting.close()
}
catch {
NSLog("Error in closing pipes in MyExtension: \(error.localizedDescription)")
}
}
It will work for i going to 0 to 1277, and fail for i == 1278. The error (obtained from strerror(errno) is Too many files open, even though there are around 6 file descriptors opened (I checked).
What am I doing wrong?
I tried to unit test the method "FilterDataProvider.handleNewFlow" from the sample project
https://developer.apple.com/documentation/networkextension/filtering_network_traffic
I always get this below issue,
Undefined symbols:
Linker command failed with exit code 1 (use -v to see invocation)
Could someone help with it?
Is there a way to change the behaviour of the toolbar back button? I would like it to be fixed to the view and not appear before. Thanks.
We are working on a command line daemon (started with launchd) for a UI to communicate with using XPC. The functions we have been using so far work correctly, but they only take arguments and return void.
We wanted to add a function with a simple reply block to see if the daemon is running or not, and we may need to get data back in the future. But it is not working.
For example, this is working:
if let proxy = connectionToService.remoteObjectProxyWithErrorHandler({ error in
print(error.localizedDescription)
}) as? TheDaemonProtocol {
proxy.doStuff("Test string")
}
But this returns an error "Couldn’t communicate with a helper application."
if let proxy = connectionToService.remoteObjectProxyWithErrorHandler({ error in
print(error.localizedDescription)
}) as? TheDaemonProtocol {
proxy.isUp { reply in
print("reply: \(reply)")
}
}
isUp() is coded to only return true for now.
@objc func isUp(reply: @escaping (Bool) -> Void) {
reply(true)
}
TIA for any help!
if I get the string contents of a PDF and print to the console in Xcode .
when run on simulator it’s fine but on device some words are missing.
same PDF, same code. only difference is simulator and physical device.
its only a word or two missing from the page.
anyone have any experience or suggestions with PDFKit to explain why a string would be missing the odd word ?
I encountered a compilation issue when trying to use my SDK built in Xcode 15.3 with Xcode 15.2 for our app. According to Apple, Swift provides ABI Stability from Xcode 12.2 onwards, so we didn't face such issues before.
Attached is the compilation error message for your reference.
SDK is built with 'Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)', while this compiler is 'Apple Swift version 5.9.2 (swiftlang-5.9.2.2.56 clang-1500.1.0.2.5)')
Hello,
I have received 3 almost identical crash reports from the App Store. They all come from the same user, and they are spaced just ± 45 seconds apart.
This is the backtrace of the crashed thread:
Crashed Thread: 3
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Termination Reason: Namespace SIGNAL, Code 6 Abort trap: 6
Terminating Process: Ssssssss [46033]
Thread 3 Crashed:
0 libsystem_kernel.dylib 0x00007ff81b90f196 __pthread_kill + 10
1 libsystem_pthread.dylib 0x00007ff81b946ee6 pthread_kill + 263 (pthread.c:1670)
2 libsystem_c.dylib 0x00007ff81b86dbdf __abort + 139 (abort.c:155)
3 libsystem_c.dylib 0x00007ff81b86db54 abort + 138 (abort.c:126)
4 libc++abi.dylib 0x00007ff81b901282 abort_message + 241
5 libc++abi.dylib 0x00007ff81b8f33fb demangling_terminate_handler() + 267
6 libobjc.A.dylib 0x00007ff81b5c67ca _objc_terminate() + 96 (objc-exception.mm:498)
7 libc++abi.dylib 0x00007ff81b9006db std::__terminate(void (*)()) + 6
8 libc++abi.dylib 0x00007ff81b900696 std::terminate() + 54
9 libdispatch.dylib 0x00007ff81b7a6047 _dispatch_client_callout + 28 (object.m:563)
10 libdispatch.dylib 0x00007ff81b7a87c4 _dispatch_queue_override_invoke + 800 (queue.c:4882)
11 libdispatch.dylib 0x00007ff81b7b5fa2 _dispatch_root_queue_drain + 343 (queue.c:7051)
12 libdispatch.dylib 0x00007ff81b7b6768 _dispatch_worker_thread2 + 170 (queue.c:7119)
13 libsystem_pthread.dylib 0x00007ff81b943c0f _pthread_wqthread + 257 (pthread.c:2631)
14 libsystem_pthread.dylib 0x00007ff81b942bbf start_wqthread + 15 (:-1)
In the backtrace of the main thread, I can see that the error is caught by the app delegate which tries to display an alert, but obviously the message has no time to appear. Incidentally (but it's not my main question), I would like to know if it would be possible in such a case to block the background thread for the time the alert is displayed (e.g. using a dispatch queue)?
... (many other related lines)
72 SSUuuuIIIIIIIIIUUuuuu 0x000000010e8089f2 +[NSAlert(Ssssssss) fatalError:] + 32
73 Ssssssss 0x000000010dd5e75b __universalExceptionHandler_block_invoke (in Ssssssss) (SQAppDelegate.m:421) + 333659
74 libdispatch.dylib 0x00007ff81b7a4d91 _dispatch_call_block_and_release + 12 (init.c:1518)
75 libdispatch.dylib 0x00007ff81b7a6033 _dispatch_client_callout + 8 (object.m:560)
76 libdispatch.dylib 0x00007ff81b7b2fcf _dispatch_main_queue_drain + 954 (queue.c:7794)
77 libdispatch.dylib 0x00007ff81b7b2c07 _dispatch_main_queue_callback_4CF + 31 (queue.c:7954)
78 CoreFoundation 0x00007ff81ba62195 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9 (CFRunLoop.c:1780)
79 CoreFoundation 0x00007ff81ba21ebf __CFRunLoopRun + 2452 (CFRunLoop.c:3147)
80 CoreFoundation 0x00007ff81ba20ec1 CFRunLoopRunSpecific + 560 (CFRunLoop.c:3418)
81 HIToolbox 0x00007ff8254a5f3d RunCurrentEventLoopInMode + 292 (EventLoop.c:455)
82 HIToolbox 0x00007ff8254a5d4e ReceiveNextEventCommon + 657 (EventBlocking.c:384)
83 HIToolbox 0x00007ff8254a5aa8 _BlockUntilNextEventMatchingListInModeWithFilter + 64 (EventBlocking.c:171)
84 AppKit 0x00007ff81eabfb18 _DPSNextEvent + 858 (CGDPSReplacement.m:818)
85 AppKit 0x00007ff81eabe9c2 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1214 (appEventRouting.m:407)
86 AppKit 0x00007ff81eab1037 -[NSApplication run] + 586 (NSApplication.m:3432)
87 AppKit 0x00007ff81ea85251 NSApplicationMain + 817 (NSApplication.m:9427)
88 dyld 0x00007ff81b5ec41f start + 1903 (dyldMain.cpp:1165)
In all 3 reports, another thread indicates that it is sending or receiving a MIDI data (it's exactly the same backtrace in the 3 reports):
Thread 1:
0 libsystem_kernel.dylib 0x00007ff81b908552 mach_msg2_trap + 10
1 libsystem_kernel.dylib 0x00007ff81b9166cd mach_msg2_internal + 78 (mach_msg.c:201)
2 libsystem_kernel.dylib 0x00007ff81b90f584 mach_msg_overwrite + 692 (mach_msg.c:0)
3 libsystem_kernel.dylib 0x00007ff81b90883a mach_msg + 19 (mach_msg.c:323)
4 CoreMIDI 0x00007ff834adfd50 XServerMachPort::ReceiveMessage(int&, void*, int&) + 94 (XMachPort.cpp:62)
5 CoreMIDI 0x00007ff834b118c5 MIDIProcess::MIDIInPortThread::Run() + 105 (MIDIClientLib.cpp:204)
6 CoreMIDI 0x00007ff834af9c44 CADeprecated::XThread::RunHelper(void*) + 10 (XThread.cpp:21)
7 CoreMIDI 0x00007ff834afae9f CADeprecated::CAPThread::Entry(CADeprecated::CAPThread*) + 77 (CAPThread.cpp:324)
8 libsystem_pthread.dylib 0x00007ff81b9471d3 _pthread_start + 125 (pthread.c:893)
9 libsystem_pthread.dylib 0x00007ff81b942bd3 thread_start + 15 (:-1)
I wonder if this MIDI activity may be related to the crash, even if it doesn't occur in the crashed thread.
I also wonder if the dispatch block starting the backtrace of the thread 3 is the same that leads to the thread 1 (to open the NSAlert), which would mean that it's after the error, or if it's a dispatch block into which the error occurs.
Finally,
2024-03-25_13-04-40.6314.crash
I wonder if std::terminate() could indicate a problem in C++ codes because I have some part of the application written in C++, and it would be a clue.
More generally, is it something in these backtraces that can help me to find what's the problem ?
Any help greatly appreciated, thanks!
-dp