Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

Memory management issue while Call Obj-C in Swift
I'm currently developing a native plugin for a Capcitor app. I have very little experience with native iOS development, Swift and Obj-C. I use a framework (FunSDK) which is written in C++. I call this in an Objective-C++ wrapper. As described here: https://medium.com/@cecilia.humlelu/set-up-c-library-dependencies-in-swift-projects-5dc2ccd2ddaf The wrapper is then available in Swift via the bridging header. This works so far, I can call the functions from the framework and they are executed correctly. However, the functions of the framework are executed asynchronously. When a result is obtained, the “OnFunSDKResult” method is always executed. During this step I get an EXC_BAD_ACCESS error while debugging. Then I ticked “Zombie objects” under the diagnostics settings. This causes execution to stop with an EXC_BREAKPOINT. As I understand it, after executing the iniXMSDK method, the FunSDKWrapper class is cleared from memory before executing the "OnFunSDKResult" method? I have also already integrated a completionHandler, which is only called in the "OnFunSDKResult" method so that data is transferred to the Swift class. However, that doesn't help either. I have no idea how to proceed. I hope somebody can help me. If you need any more information, I would be happy to provide it. The FunSDKWrapper.mm // // FunSDKWrapper.m // App // // Created by Sysprobs on 12/8/23. // #import "FunSDKWrapper.h" #import "FunSDK/FunSDK.h" #import <XMNetInterface/Reachability.h> @implementation FunSDKWrapper -(NSString *)iniXMSDK:(int)test completion:(void (^)(int result))completionHandler{ self.initCompletionHandler = completionHandler; self.msgHandle = FUN_RegWnd((__bridge void *)self); FUN_Init(); Fun_LogInit(self.msgHandle, "", 0, "", LOG_UI_MSG); FUN_XMCloundPlatformInit("***", "***", "***", 1); FUN_InitNetSDK(); FUN_SetFunStrAttr(EFUN_ATTR_SAVE_LOGIN_USER_INFO,SZSTR([self GetDocumentPathWith:@"UserInfo.db"])); FUN_SetFunStrAttr(EFUN_ATTR_USER_PWD_DB, SZSTR([self GetDocumentPathWith:@"password.txt"])); FUN_SetFunStrAttr(EFUN_ATTR_UPDATE_FILE_PATH,SZSTR([self GetDocumentPathWith:@""])); FUN_SetFunStrAttr(EFUN_ATTR_TEMP_FILES_PATH,SZSTR([self GetDocumentPathWith:@""])); FUN_SetFunIntAttr(EFUN_ATTR_AUTO_DL_UPGRADE, 0); FUN_SetFunStrAttr(EFUN_ATTR_CONFIG_PATH,SZSTR([self GetDocumentPathWith:@"APPConfigs"])); FUN_SetFunIntAttr(EFUN_ATTR_SUP_RPS_VIDEO_DEFAULT, 1); FUN_SetFunIntAttr(EFUN_ATTR_SET_NET_TYPE, [self getNetworkType]); FUN_SysInit("arsp.xmeye.net;arsp1.xmeye.net;arsp2.xmeye.net", 15010); FUN_InitNetSDK(); FUN_SysGetDevList(self.msgHandle, SZSTR(@"xxxx") , SZSTR(@"xxxx"),0); return @"test"; } - (void)searchLanDevices { FUN_DevSearchDevice(self.msgHandle, 4000, 0); } // NSDocument/fileName - (NSString *)GetDocumentPathWith:(NSString *) fileName { NSString* path = [self documentsPath]; if (fileName != nil) { path = [path stringByAppendingString:@"/"]; path = [path stringByAppendingString:fileName]; } return path; } //NSDocument - (NSString *)documentsPath { NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path = [pathArray lastObject]; return path; } -(int)getNetworkType { Reachability*reach=[Reachability reachabilityWithHostName:@"www.apple.com"]; //判断当前的网络状态 switch([reach currentReachabilityStatus]){ case ReachableViaWiFi: return 1; case ReachableViaWWAN: return 2; default: return 0; break; } } - (void)OnFunSDKResult:(NSNumber *) pParam { NSInteger nAddr = [pParam integerValue]; MsgContent *msg = (MsgContent *)nAddr; switch (msg->id) { case EMSG_SYS_GET_DEV_INFO_BY_USER:{ self.initCompletionHandler(1); if (msg->param1 < 0){ //fehler NSLog(@"Fehler beim XMCloud login"); }else{ char devJson[750*500]; FUN_GetFunStrAttr(EFUN_ATTR_GET_USER_ACCOUNT_DATA_INFO, devJson, 750*500); NSLog(@"Geraeteliste: = %s",devJson); } } break; } } @end The Swift Class import Foundation import Capacitor /** * Please read the Capacitor iOS Plugin Development Guide * here: https://capacitorjs.com/docs/plugins/ios */ @objc(xmsdkPlugin) public class xmsdkPlugin: CAPPlugin { private let implementation = xmsdk() @objc func echo(_ call: CAPPluginCall) { let value = call.getString("value") ?? "" call.resolve([ "value": implementation.echo(value) ]) } @objc func initXMSDK(_ call: CAPPluginCall) { //let devId = call.getString("devId") ?? "" let wrapper = FunSDKWrapper(); let resp = wrapper.iniXMSDK(1, completion: {(result) -> Void in NSLog("Completion von iniXMSDK") }); call.resolve([ "status": resp ]) } } Errorlog with EXC_BREAKPOINT:
1
0
420
Dec ’23
Environment variable not working in another user account
I have the following in my .zshrc: export MY_LIBRARY_DIR=~/bin In Xcode I can set header/lib search path using something like $(MY_LIBRARY_DIR)/abc. This works fine in my daily used user account. But today I found that this technique does not work in a test user account (for testing purpose only). I even reboot my machine but still can't get it working. Am I missing something very obvious??? BTW, I am using Xcode 14.2 and 14.3.1.
1
0
576
Dec ’23
Connect CoreData Container to SwiftData Container
I wrote an application using SwiftData to store data. But now I have rewritten it to CoraData because I would like to expand the list of available devices for downloading. All model classes have retained their names and all parameters too, but I don’t see data from the previous version. Is it possible to get into the same container? Maybe someone can tell me the name of the default container that is created by SwiftData.
0
0
380
Dec ’23
Simple scriptable macOS Xcode Swift App example please
Does anyone have a simple example for a scriptable App in Swift in Xcode for macOS? I mean one that exposes objects and functions to applescript? I've checked all examples that I could find. But for me they get me confused about whether they are accessing the actual and already existing instance of a class or whether they are creating an instance with AppleScript, or just using the class definition to call some function. Also the way they are defined in the .sdef file does not help. It would be great if someone had a really simple example, stripped down to bare minimum that 1) defines a class with a single function, 2) creates an instance of the class inside appDelegate and then 3) the function of the specific instance is called using appleScript. 4) It would be great if the function could do something in the GUI, such as change a text of a Label.
0
0
665
Dec ’23
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
405
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
375
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
571
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
479
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
967
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
763
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
579
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
481
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.1k
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
636
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
797
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
401
Dec ’23