Dive into the world of programming languages used for app development.

All subtopics

Post

Replies

Boosts

Views

Activity

Resetting position and size of SKSpriteNodes with *every* rotation??
Do I really have to reset position and size of SKSpriteNodes with every rotation between landscape and portrait layout?? I've done that and it works .. but this seems to be overkill that the writers of Xcode internally compensated for .. vs. having the individual programmer having to do it. I have a getGameParms() which resets positions based on: #if os(iOS) && !targetEnvironment(macCatalyst) func getGameParms() { let roomRect = UIScreen.main.bounds roomWidth = roomRect.width * roomScale roomHeight = roomRect.height * roomScale if (thisSceneName == "GameScene") { if UIDevice.current.orientation.isLandscape { // changes here } else { // changes } } // if (thisSceneName == "GameScene") } // getGameParms #elseif os(tvOS) func getGameParms() { let roomRect = UIScreen.main.bounds roomWidth = roomRect.width * roomScale roomHeight = roomRect.height * roomScale if (thisSceneName == "GameScene") { // other changes here } } // getGameParms #endif Again, the burdensome changes are done .. but are they really necessary? As an alternative, I have called getGameParms() just once within my viewDidLoad() and the results are not correct. For example, I place one SKSpriteNode at the very bottom of the UIScreen and it does not stay there with UIDevice rotation. I also size it horizontally such that it expands to the full width of the UIScreen. Rotation destroys that. if getGameParms() is called only once as just described. Some explanation as to why would be appreciated.
0
0
408
Dec ’23
No member in framework target: Swift class as forward class in ObjC, accessed in Swift through ObjC class
So I am creating an ObjC framework which has mix of ObjC and Swift code: UtilitiesFramework. Here is my StringUtilities class in Swift: @objc public class StringUtilities: NSObject { } I am accessing StringUtilities class in Utilities which is an ObjC class. Here is Utilities.h which is returning StringUtilities and has a forward class declaration for same: @class StringUtilities; // Forward Declaration @interface Utilities: NSObject - (StringUtilities *)stringUtilities; @end Here is Utilities.m which imports generated swift header file: #import <UtilitiesFramework/UtilitiesFramework-Swift.h> // This should provide concrete implementation of StringUtilities @implementation Utilities - (StringUtilities *)stringUtilities { return [StringUtilities new]; } @end I am exposing Utilites.h file to Swift through module.modulemap: module PrivateObjC { header "Utilities.h" } I have set the import path accurately in build settings as: $(SRCROOT)/$(PRODUCT_NAME) Now when I try to access Utilities class in some other swift class it just compiles fine: import PrivateObjC class SomeOperations { func doSomething() { _ = Utilities() // This compiles fine } However when I try to access the StringUtilities through its method, it gives compilation error: import PrivateObjC class SomeOperations { func doSomething() { _ = Utilities().stringUtilities() // This gives compilation error } Here are the errors: value of type Utilities has no member stringUtilities: _ = Utilities().stringUtilities() note: method stringUtilities not imported - (StringUtilities *)stringUtilities ^ note: return type not imported - (StringUtilities *)stringUtilities ^ note: interface StringUtilities is incomplete - (StringUtilities *)stringUtilities ^ note: interface StringUtilites forward declared here @class StringUtilities I thought this scenario is fixed as part of proposal: # 0384-importing-forward-declared-objc-interfaces-and-protocols.md However it is not working for me. May be it is due to it being approved as part of Swift 5.9, whereas in my machine 5.8.1 is used or am I missing anything else over here? Update: I installed Xcode 15 and double checked the swift version which is 5.9, however I am still getting the error. Any idea why it is not working for a framework target?
0
0
382
Dec ’23
UIBezierPath *not* showing?
I am developing a game in which my Locomotive is following a UIBezierPath that mimics an oval shaped Track. The math of the following is not "adding up" .. if it is, I am obviously not understanding the math of the layout. Bottom line = the following code does not display the UIBezierPath. Here's the code that creates this UIBezierPath .. please note the math in the comments: func createTrainPath() { trackRect = CGRect(x: 0.0, y: 0.0 - roomHeight/2 + tracksHeight, width: tracksWidth, height: tracksHeight) // trackRect = (0.0, -207.0, 940.0, 476.0) // portrait // trackRect = (0.0, -274.0, 470.0, 238.0) // landscape print("trackRect = \(trackRect!)") trackPath = UIBezierPath(ovalIn: trackRect) let theTrackShapeNode = SKShapeNode(path: trackPath.cgPath, centered: true) theTrackShapeNode.zPosition = 100 // for testing theTrackShapeNode.position = myTracks.position theTrackShapeNode.lineWidth = 4.0 theTrackShapeNode.strokeColor = SKColor.blue if let ourScene = GameScene(fileNamed: "GameScene") { print("here") // this shows ourScene.addChild(theTrackShapeNode) // does *not* show? } } // createTrainPath In Portrait mode, the UIScreen measures 1024 x 1366 and the Track measures 940 x 476 with its top edge down 207 from the center of the UIScreen. In Landscape mode, the UIScreen measures 1366 x 1024 and the Track measures 470 x 238 with its top edge down 274 from the center of the UIScreen. In both modes, the bottom edge of the Track is supposed to be flush with the bottom edge of the UIScreen .. and it is. If the math is correct, then I am obviously not understanding the math of the layout .. because the UIBezierPath is not showing. The math appears correct .. but the UIBezierPath just is not showing. So where is my brain off-center?
3
0
577
Dec ’23
share photo to facebook but no dialog shows
Hi, Everyone I set up a class for sharing photos to facebook. The codes of the class are as following. But when I call the function "shareToFacebook", there is no dialog to show. What's the issue in these codes? I am using iOS 17.0, Xcode The guide from Facebook hasn't updated. import SwiftUI import FBSDKShareKit import FacebookShare @Observable class ShareFacebook { var content = SharePhotoContent() var images : [UIImage] = [] var photos : [SharePhoto] = [] func shareToFacebook() { for image in images { let photo = SharePhoto( image: image, isUserGenerated: true ) photos.append(photo) } content.photos = photos let dialog = ShareDialog( viewController: UIApplication.shared.currentUIWindow()?.rootViewController, content: content, delegate: nil ) dialog.show() } } //button for sharing //Sharing to Facebook Button { for image in photos { let image = UIImage(data: image.imageData) sharedPhotos.append(image ?? userViewModel.render(image: Image("photoForNil"))! ) } shareToFacebook.images = sharedPhotos shareToFacebook.shareToFacebook() }label: { Image("share") .resizable() .frame(width:18, height: 18) .padding(.trailing,30) }
0
0
482
Dec ’23
Symbol not found: _swift_getTypeByMangledNameInContext2
We have MacOS application which uses Network Extensions. When building it with XCode 15 and 15.0.1 the extension crashes on Intel based Macs with the following error: Symbol not found: _swift_getTypeByMangledNameInContext2 Expected in: /usr/lib/swift/libswiftCore.dylib We tested it on Big Sur and Ventura with the same outcome. On Ventura when running on Intel based Mac libswiftCore.dylib really doesn't provide this symbol: nm -g libswiftCore.dylib | grep Mangle 00007ff80faf6150 T _$ss031_getFunctionFullNameFromMangledD007mangledD0SSSgSS_tF 00007ff80fcc4460 T _swift_getFunctionFullNameFromMangledName 00007ff80fcc40b0 T _swift_getMangledTypeName 00007ff80fcf7ed0 T _swift_getTypeByMangledName 00007ff80fcf8230 T _swift_getTypeByMangledNameInContext 00007ff80fcf8370 T _swift_getTypeByMangledNameInContextInMetadataState 00007ff80fcf7d90 T _swift_getTypeByMangledNameInEnvironment 00007ff80fcf80f0 T _swift_getTypeByMangledNameInEnvironmentInMetadataState 00007ff80fcfb460 T _swift_getTypeByMangledNode Is there any workaround for this issue? Crash log is the following: Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 dyld 0x000000010a165f7a __abort_with_payload + 10 1 dyld 0x000000010a18ef40 abort_with_payload_wrapper_internal + 80 2 dyld 0x000000010a18ef72 abort_with_payload + 9 3 dyld 0x000000010a10f14a dyld::halt(char const*) + 672 4 dyld 0x000000010a10f274 dyld::fastBindLazySymbol(ImageLoader**, unsigned long) + 167 5 libdyld.dylib 0x00007fff203b3376 dyld_stub_binder + 282 6 ??? 0x0000000104b086a0 0 + 4373644960 7 com.xxxx.Tunnel 0x00000001049d318a 0x10489e000 + 1266058 8 com.xxxx.Tunnel 0x00000001049df35d 0x10489e000 + 1315677 9 com.xxxx.Tunnel 0x00000001048a0765 0x10489e000 + 10085 10 com.apple.ExtensionKit 0x00007fff31bda683 __112-[EXConcreteExtensionContextVendor _beginRequestWithExtensionItems:listenerEndpoint:withContextUUID:completion:]_block_invoke + 808 11 libdispatch.dylib 0x00007fff201ec5dd _dispatch_call_block_and_release + 12 12 libdispatch.dylib 0x00007fff201ed7c7 _dispatch_client_callout + 8 13 libdispatch.dylib 0x00007fff201f9b86 _dispatch_main_queue_callback_4CF + 940 14 com.apple.CoreFoundation 0x00007fff204ce356 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9 15 com.apple.CoreFoundation 0x00007fff20490188 __CFRunLoopRun + 2745 16 com.apple.CoreFoundation 0x00007fff2048efe2 CFRunLoopRunSpecific + 567 17 com.apple.Foundation 0x00007fff21151fa1 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 212 18 com.apple.Foundation 0x00007fff211e0384 -[NSRunLoop(NSRunLoop) run] + 76 19 libxpc.dylib 0x00007fff200e53dd _xpc_objc_main + 825 20 libxpc.dylib 0x00007fff200e4e65 xpc_main + 437 21 com.apple.Foundation 0x00007fff211732bd -[NSXPCListener resume] + 262 22 com.apple.pluginkit.framework 0x00007fff2b288273 0x7fff2b26d000 + 111219 23 com.apple.pluginkit.framework 0x00007fff2b287efb 0x7fff2b26d000 + 110331 24 com.apple.pluginkit.framework 0x00007fff2b288639 0x7fff2b26d000 + 112185 25 com.apple.ExtensionKit 0x00007fff31be6d05 EXExtensionMain + 70 26 com.apple.Foundation 0x00007fff211e2479 NSExtensionMain + 208 27 libdyld.dylib 0x00007fff203b4621 start + 1
4
0
988
Dec ’23
StoreKit sample project from Apple fails concurrency checks
I am trying to use code from Apple's sample project on StoreKit (Implementing a store in your app using the StoreKit API). However, even if I don't make any changes to this sample project except enable "complete" concurrency checking in the build settings, I get warnings like Capture of 'self' with non-sendable type 'Store' in a '@Sendable' closure. How worried should I be about these warnings and how can I fix them?
1
0
772
Dec ’23
localizedCallerName is not updated in iOS 17.2
CallKit is not get updated on iPhone 14 with Dynamic Island When I am receiving incoming call I need to update localizedCallerName in CallKit. As of iOS 17.2, localizedCallerName does not change. Is there anything I need to specify to update the name? Looks like the problem is related to CXCallUpdate() This is the code I use for updating caller name: func updateCallerName(_ call: Call) { let update = CXCallUpdate() update.localizedCallerName = call.localizedCallerName cxProvider.reportCall(with: call.uuid, updated: update) }
1
1
591
Dec ’23
localizedCallerName does not change in incoming call banner in iOS 17.2
When I am receiving incoming call I need to update localizedCallerName in CallKit. As of iOS 17.2, localizedCallerName does not change. Is there anything I need to specify to update the name? Looks like the problem is related to CXCallUpdate() This is the code I use for updating caller name: func updateCallerName(_ call: Call) { let update = CXCallUpdate() update.localizedCallerName = call.localizedCallerName provider.reportCall(with: call.uuid, updated: update) }
1
1
488
Dec ’23
Modifications to the layout engine must not be performed from a background thread on iOS 17 and above
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread. I have been experiencing frequent crashes on iOS 17 and above recently, and I'm having trouble pinpointing the source of the crashes. The crash logs provide no information about the specific location of the crashes. Is there any workaround or solution to identify and resolve this issue? Please find attached the crash logs below
2
0
1.2k
Dec ’23
Temperature was not able to be retrieved
0 I am building a simple macOS menu bar app in swift that displays my machine's CPU temperature and I'm just testing out my function to make sure it can retrieve the temp and display it in the Xcode terminal but instead my error handler messages are triggered indicating an issue retrieving my machines CPU temp data "CPU temp °F could not be retrieved temps couldnot be displayed" import Cocoa import IOKit import IOKit.ps class CPUTempWithServiceMatching { static func getCPUTemp() -> Double? { let dictionaryMatching = IOServiceMatching("AppleSMC") var service = IOServiceGetMatchingService(kIOMainPortDefault, dictionaryMatching) var temp = "0.0" if service != 0 { let key = "TC0P" //thermal zone zero proxy if let result = IORegistryEntryCreateCFProperty(service, key as CFString, kCFAllocatorDefault, 0 ) { temp = (result.takeUnretainedValue() as! NSNumber).doubleValue.description IOObjectRelease(service) if let CPUTemp = Double(temp) { print("CPU Temp: \(CPUTemp) °F") return(CPUTemp) } } print("CPU temp °F could not be retrieved") } return nil } } @main struct program { static func main() { if let cpuTemp = CPUTempWithServiceMatching.getCPUTemp() { print("cpu temp\(cpuTemp) °F") } else { print("temps couldnot be displayed") } } }
1
0
642
Dec ’23
sudo from swift MacOS app
Hi, I'm working in a MacOS Swift app that uses hdiutil and asr. Although I can send the sudo credentials and it can be read perfectly in the terminal, sometimes it appears that they are not enough to allow the program to run, throwing the following error: (asr) Failed to create source stream for replication Volume replication failed - Operation not permited This seems to be a permisions issue, because the very same code run perfectly when it is started from the terminal (szh). What would be the most practical way to overcome this issue? Any help will be highly appreciated.
4
0
808
Dec ’23
How to translate data from c language void * pointer to [UInt8 ] in swift code.
A swift function name as getDataFromC which can connect with C function. A C function name as ExternalMethod which will receive the connect from swift. The parameter will be fill by call setData function. I can confirm that the entire structure return to getDataFromC was successful. Because I print the data of other structure members to check the correctness of the data. However, I don't know how to translate the largeData to [UInt8]. I try UnsafeMutableRawPointer type. I don't know what to do for the following action. I expected that output.largeData can be translate to [UInt8] type. //Bridging header file struct myStruct { void *largeData; int largeDataLength; int smallData[3]; } //C file void setData(myStruct* data) { int i = 0; uint8_t array[1024]; memset(array,0x66,1024); data->largeData = array; data->largeDataLength = 1024; data->smalData[0] = 0x99; data->smalData[0] = 0x88; data->smalData[0] = 0x77; } void ExternalMethod(myStruct* data) { setData(&output); } //Swift file func test() { var output = myStruct() getDataFromC(&output); var myPointer: UnsafeMutableRawPointer = output.largeData /* Here: I don't know how to translate data from myPointer to [UInt8] */ print("smallData: \(output.largeDataLength)") // 1024 transmission is correct print("smallData: \(output.smallData.0)") // 0x99 transmission is correct print("smallData: \(output.smallData.1)") // 0x88 transmission is correct print("smallData: \(output.smallData.2)") // 0x77 transmission is correct }
2
0
408
Dec ’23
Double value cannot be converted to UInt8 because the result would be less than UInt8.min
I have a swift callback function that accumulates data from the gyroscope handler CMGyroData to value, and takes care that it never goes below zero. Any thoughts why I got this crash? var value: Double = 90 func test(d: Double) { value -= d if value < 0 { value = 0 } else if value > 180 { value = 180 } // Double value cannot be converted to UInt8 because the result would be less than UInt8.min // according to Xcode, value is 0 let angle = UInt8(value.rounded()) print(angle) } During the crash, the debugger shows that value is 0, and the raw memory is 0x0000000000000000. I've heard about negative zero, but then the raw memory would be 0x8000000000000000. Either way, it makes no sense for the UInt8 constructor to fail. (lldb) p value (Double) 0 (lldb) p value.rounded() (Double) 0 (lldb) p UInt8(value.rounded()) (UInt8) 0 Xcode 15.1, iPhone 7 Plus, iOS 15.8 Edit: As a good measure, I changed that line to let angle = UInt8(Int(value.rounded()))
7
0
1.4k
Dec ’23
How to access a directly attached UVC camera with AVPlayer?
On macOS Sonoma I have a SwiftUI app that correctly plays remote video files and local video files from the app bundle. Where I'm having trouble is setting up the AVPlayer URL for a UVC camera device directly connected on the Mac. let url = URL(string: "https://some-remote-video.mp4")! player = AVPlayer(url: url) player.play() Is there some magic to using a UVC device with AVPlayer, or do I need to access the UVC device differently? Thanks, Grahm
1
0
761
Dec ’23
How to debugging EXC_BAD_ACCESS KERN_INVALID_ADDRESS
Hi all, I'm trying to find the reason why my app is crashing and fix it. This is just happening in some devices and others are working fine. I have no idea how to do it and any hint on what to do will be really appreciated. I am in a test stage using testFlight and I am using crashlytics to collect the errors. The apps has Firebase services (Push Notification, firestore, crashlytics) google maps, Realm and more. The error is below: EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000018 Crashed: com.apple.main-thread 0 myapp 0x3dcd4c gmscore::vector::TextureAtlasElement::height() const + 72916 1 myapp 0xe9e50 (anonymous namespace)::BubbleBehavior::Commit(gmscore::renderer::EntityRenderer*) + 4373995088 2 myapp 0x2d14ac gmscore::renderer::EntityRenderer::Draw(bool, bool) + 340 3 myapp 0x39d2dc -[GMSPhoenixRenderer drawForced:deferredPresentation:] + 13156 4 myapp 0x37ed2c -[GMSEntityRendererView draw] + 116072 5 myapp 0x3c2aa0 -[GMSVectorMapView draw] + 166696 6 myapp 0x37d140 -[GMSEntityRendererView displayLinkFired:] + 108924 7 myapp 0x37b4a8 -[GMSDisplayLink displayLinkFired:] + 101604 8 QuartzCore 0x2fa14 CA::Display::DisplayLinkItem::dispatch_(CA::SignPost::Interval<(CA::SignPost::CAEventCode)835322056>&) + 48 9 QuartzCore 0x32bfc CA::Display::DisplayLink::dispatch_items(unsigned long long, unsigned long long, unsigned long long) + 864 10 QuartzCore 0x32708 CA::Display::DisplayLink::callback(_CADisplayTimer*, unsigned long long, unsigned long long, unsigned long long, bool, void*) + 844 11 QuartzCore 0xb191c CA::Display::DisplayLink::dispatch_deferred_display_links(unsigned int) + 348 12 UIKitCore 0xaa48c _UIUpdateSequenceRun + 84 13 UIKitCore 0xa9b7c schedulerStepScheduledMainSection + 144 14 UIKitCore 0xa9c38 runloopSourceCallback + 92 15 CoreFoundation 0x3731c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 16 CoreFoundation 0x36598 __CFRunLoopDoSource0 + 176 17 CoreFoundation 0x34d4c __CFRunLoopDoSources0 + 244 18 CoreFoundation 0x33a88 __CFRunLoopRun + 828 19 CoreFoundation 0x33668 CFRunLoopRunSpecific + 608 20 GraphicsServices 0x35ec GSEventRunModal + 164 21 UIKitCore 0x22c2b4 -[UIApplication _run] + 888 22 UIKitCore 0x22b8f0 UIApplicationMain + 340 23 UIKitCore 0x4559c8 __swift_destroy_boxed_opaque_existential_1Tm + 12220 24 myapp 0x34704 main + 4373251844 (AppDelegate.swift:4373251844) 25 ??? 0x1bb0badcc (Falta)
2
0
1.2k
Dec ’23
Using URLRequest with AVPlayer
I'm creating an app with a video player streaming video from an URL. The AVPlayer only takes the URL address of the video but I'd like to create a custom URLRequest and then use that to stream the video from online. So current situation is this: let videourl = URL(string: "videofoobar.com") let player = AVPlayer(url: videourl) player.play() And I would like to go to something like this: let videourl = URL(string: "videofoobar.com") var request = URLRequest(url: videourl) let player = AVPlayer(request: request) //This obviously fails, any workaround? player.play() I know it is not possible to do it like this as AVPlayer only takes URL or AVPlayerItem as parameter. Is there any workaround to make URLRequest and then give it to AVPlayer for online streaming?
0
0
571
Dec ’23
Error booting app with Transformer in SwiftData Class
Hi folks, I'm trying to use a Transformer in a SwiftData class, but everytime i boot the app in the visionOS simulator it shows an error in main. Error: Thread 1: Fatal error: Application must register a ValueTransformer for NSAttributedStringTransformer Here's my main file: @main struct TestApp: App { var body: some Scene { WindowGroup(id: "main") { InfoWindow() .modelContainer(for: Document.self) } .windowResizability(.contentSize) } } Here's the class file: import SwiftData @Model final class Document { @Attribute(.unique) var id: String @Attribute(.transformable(by: NSAttributedStringTransformer.self)) var content: NSAttributedString var name: String var history: [String] init(content: NSAttributedString, name: String, history: [String]) { self.id = UUID().uuidString self.content = content self.name = name self.history = history } } extension Document: Identifiable { } } And the Transformer: extension NSValueTransformerName { static let nsAttributedStringTransformer = NSValueTransformerName(rawValue: "NSAttributedStringTransformer") } @objc(NSAttributedStringTransformer) class NSAttributedStringTransformer: NSSecureUnarchiveFromDataTransformer { override class func allowsReverseTransformation() -> Bool { return true } override class var allowedTopLevelClasses: [AnyClass] { return [NSAttributedString.self] } override class func transformedValueClass() -> AnyClass { return NSAttributedString.self } override func reverseTransformedValue(_ value: Any?) -> Any? { guard let attributedString = value as? NSAttributedString else { return nil } return attributedString.toNSData() } override func transformedValue(_ value: Any?) -> Any? { guard let data = value as? NSData else { return nil } return data.toAttributedString() } } private extension NSData { func toAttributedString() -> NSAttributedString? { let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [ .documentType: NSAttributedString.DocumentType.rtf, .characterEncoding: String.Encoding.utf8 ] return try? NSAttributedString(data: Data(referencing: self), options: options, documentAttributes: nil) } } private extension NSAttributedString { func toNSData() -> NSData? { let options: [NSAttributedString.DocumentAttributeKey: Any] = [ .documentType: NSAttributedString.DocumentType.rtf, .characterEncoding: String.Encoding.utf8 ] let range = NSRange(location: 0, length: length) guard let data = try? data(from: range, documentAttributes: options) else { return nil } return NSData(data: data) } } Been stuck in this issue for a while now and would appreciate if anyone with more experience could help!
0
0
388
Dec ’23