Objective-C

RSS for tag

Objective-C is a programming language for writing iOS, iPad OS, and macOS apps.

Posts under Objective-C tag

220 Posts
Sort by:
Post not yet marked as solved
1 Replies
266 Views
I have an uncommon scenario here. outer tableview +--------------------------+ | column 1| inner tableview| +--------------------------+ Now most often the out tableview has many rows and vertical scrollbar visible. When user try to scroll vertically in the inner tableview but it has no vertical scrollbar (because it has only a few items), I want the scroll event sink into its parent view or better outer tableview, so that user does not have to move cursor to first column in outer tableview and scrolls. Is this possible?
Posted
by imneo.
Last updated
.
Post not yet marked as solved
0 Replies
180 Views
To me, the documentation for this method is not at all clear and needs to provide sample code. I tried searching the dev site for sample projects, but they're no longer where they lived for decades before. And where's the TextEdit sample project?! I need to override shouldCloseWindowController so I can make sure some sub-windows can be closed before closing the document's one and only window. I've done that, but then have no idea what I'm supposed to do to all the document to close. I tried this, which is what I think the NSDocument version header says to do: if ((self.windowControllers.first?.shouldCloseDocument) != nil){ self.canClose(withDelegate:delegate as Any, shouldClose:shouldCloseSelector, contextInfo:contextInfo); } But the document never gets the close() method called - only the window goes away.
Posted
by sjmills.
Last updated
.
Post not yet marked as solved
2 Replies
680 Views
In the context of a system utility that reports OS stats periodically, the security type for a connected WiFi network could be obtained with Core WLAN via CWInterface.security. This used to work up to Ventur; howver, after upgrading to Sonoma, cwInterface.security now returns kCWSecurityUnknown. In other posts, I have read about changes in how Core WLAN works which are related to Sonoma. How can I determine the security type for a connected WiFi network on Sonoma? It would be preferable if the suggested approach would also work on previous macOS versions as well. Many thanks in advance! :-)
Posted
by fsauter.
Last updated
.
Post not yet marked as solved
0 Replies
169 Views
Hi, I have implemented VOIP calling feature in my application using OpenTok SDK and CallKit framework. Calling feature is working most of the time. But there is one strange issue I have come across. During a call, if any external cellular call appears and if I decline that external call then my running voip call also disconnects. This is happening some of the iPhone devices. iPhone config: Model: iPhone 11 iOS Version: 17.3 I have added loggers CXEndCallAction and -provider:performEndCallAction and debugged at my end. I found that CXEndCallAction is not executing from my end but still -provider:performEndCallAction is triggered by iOS along with my ongoing callUUID. This is very strange behaviour I am observing in one of my iPhone device. I have tested this in 4 iPhone devices but i am facing this issue only in 1 iPhone. Thanks,
Posted Last updated
.
Post marked as solved
1 Replies
273 Views
I have a custom Objective-C ObjectCache class that utilized NSMutableDictionary to store named objects (specifically large NSImage objects). The class has a maxItems property and clear method, which worked fine. - (void)clear { @synchronized(_cache) { [_cache removeAllObjects]; } } But yesterday I received a customer feedback complaining one of my app consumes up to 24GB memory. I verified that on my M1 Mac mini, and it's true. Even after calling clear method, memory usage shown in both Xcode debugger panel and Activity Monitor remains the same. It did work before. Once I close a picture gallery window by calling clear method, memory usage dropped immediately as shown in Activity Monitor. I suspect that this is a bug in ARM architecture. Does anyone else have same problem?
Posted
by imneo.
Last updated
.
Post not yet marked as solved
0 Replies
291 Views
I'm currently using a WKWebView to load certain types of documents via loadRequest, but I've recently been running into an issue with .doc files doing this: static NSString *customScheme = @"customscheme"; @interface WordDocWKSchemeHandler : NSObject <WKURLSchemeHandler> @end @implementation WordDocWKSchemeHandler { NSData *_data; NSString *_mimeType; } - (instancetype)initWithData:(NSData*)data mimeType:(NSString*)mimeType{ self = [super init]; if (self) { _data = data; _mimeType = mimeType; } return self; } - (void)webView:(WKWebView *)webView startURLSchemeTask:(id<WKURLSchemeTask>)urlSchemeTask { NSURL *url = urlSchemeTask.request.URL; if (![url.scheme isEqualToString:customScheme]){ return; } NSURLResponse *response = [[NSURLResponse alloc] initWithURL:url MIMEType:_mimeType expectedContentLength:_data.length textEncodingName:@""]; [urlSchemeTask didReceiveResponse:response]; [urlSchemeTask didReceiveData:_data]; [urlSchemeTask didFinish]; } - (void)webView:(WKWebView *)webView stopURLSchemeTask:(id<WKURLSchemeTask>)urlSchemeTask{ //empty } @end - (void)_setupWebViewPropertiesAndConstraints{ _webView.navigationDelegate = self; _webView.hidden = YES; [self.view addConstrainedSubview:_webView]; [self.view addConstraints:[_webView constraintsForFillingSuperview]]; self.container.showsLoadingIndicator = YES; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; WKWebViewConfiguration *docConfig = [WKWebViewConfiguration new]; WordDocWKSchemeHandler *schemeHanlder = [[WordDocWKSchemeHandler alloc] initWithData:_content.data mimeType:_content.contentType]; [docConfig setURLSchemeHandler:schemeHanlder forURLScheme:customScheme]; //Setup webview with custom config handler _webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:docConfig]; [self _setupWebViewPropertiesAndConstraints]; NSURL *customURL = [NSURL URLWithString:[NSString stringWithFormat:@"\%@:/",customScheme]]; [_webView loadRequest:[NSURLRequest requestWithURL:customURL]]; } The mimeType is correctly being resolved to "application/msword" but any time we try to load this the navigation fails: -(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error { The error message here is OfficeImportErrorDomain Code=912. I've tried this on both a simulator and actual device on iOS 17 and 16 and this always fails. I've also tried turning the data into a base64 string and loading it that way and this also fails. Any advice here would be appreciated. It seems like this used to work at some point but no longer works.
Posted Last updated
.
Post not yet marked as solved
0 Replies
214 Views
Hello, I have some older objective-c projects that are about creating reports of tables and gantt charts and printing those reports. They work fine on Ventura and BigSur, but after upgrading to Sonoma, I encountered some problems with the Print dialog and options. Specifically, the page preview is not working, and the Close button does not close the dialog and is not responsive. I have to force quit the app to exit the Print dialog. This makes it impossible to print my reports properly. I wonder if this is a bug with Sonoma or with objective-c, and if there is any workaround or fix for this issue. I appreciate any help or advice from the community or the Apple support team. Thank you.
Posted
by _Filip_.
Last updated
.
Post not yet marked as solved
7 Replies
336 Views
I have an app which uses Cocoa Pods to use MQTTClient in connecting to io.adafruit. I use the app to get the various data point stored at io.adafruit and to even send data to adafruit to control a connected unit. I am using .xcworkspace to upload the app on my phone and everything works fine. I am hoping to wake my app every so ofter to get some data points from io.adafruit and if certain conditions exist, I want to send a notification to the user. I have added Background Modes to my app's Signing & Capabilities (Background fetch) and in my INFO I have Permitted background task scheduler identifiers with the String identifier LEVELIT.Refresh. The following is my code I am using in my AppDelegate.h #import <UIKit/UIKit.h> #import <CoreData/CoreData.h> #import <MQTTClient/MQTTClient.h> #import <UserNotifications/UserNotifications.h> @interface AppDelegate: UIResponder <UIApplicationDelegate, UNUserNotificationCenterDelegate,UIAlertViewDelegate,MQTTSessionDelegate>{ MQTTSession *session3; } @property (nonatomic, retain) MQTTSession *session3; @property (nonatomic, strong) NSPersistentContainer *persistentContainer; @end And this is the code I use in my AppDelegate.m #import "AppDelegate.h" #import <BackgroundTasks/BackgroundTasks.h> #import <CloudKit/CloudKit.h> #import <UserNotifications/UserNotifications.h> static NSString* TaskID = @"LEVELIT.refresh"; @interface AppDelegate() @property (nonatomic, retain) NSString *myUserName; @property (nonatomic, retain) NSString *myUserKey; @property (nonatomic, retain) NSString *myTrips; @property (nonatomic, retain) NSString *atrip; @property (nonatomic, retain) NSString *trip; @property (nonatomic, retain) NSString *gettrip; @property(strong) void (^expirationHandler)(void); @end @implementation AppDelegate @synthesize session3,window; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if (@available(iOS 13.0, *)) { [[BGTaskScheduler sharedScheduler] registerForTaskWithIdentifier:TaskID usingQueue:nil launchHandler:^(BGAppRefreshTask *task) { [self handleAppRefreshTask:task]; }]; } else { // Fallback on earlier versions } UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) { }]; UNNotificationCategory* generalCategory = [UNNotificationCategory categoryWithIdentifier:@"GENERAL" actions:@[] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction]; NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults]; if([[[defaults2 dictionaryRepresentation] allKeys] containsObject:@"myUserNameFile"]){ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; self.myUserName = [defaults objectForKey:@"myUserNameFile"]; NSLog(@"myUserName1:%@",self.myUserName); self.myUserKey = [defaults objectForKey:@"myUserKeyFile"]; NSLog(@"myUserKey1:%@",self.myUserKey); } return YES; } } -(void)schedualLocalNotifications{ } - (void)setTaskCompletedWithSuccess:(BOOL)success;{ NSLog(@"Completed"); } - (void)applicationDidEnterBackground:(UIApplication *)application { NSLog(@"Entering background"); if (@available(iOS 13.0, *)) { BGAppRefreshTaskRequest *request = [[BGAppRefreshTaskRequest alloc] initWithIdentifier:TaskID]; request.earliestBeginDate = [NSDate dateWithTimeIntervalSinceNow:15*60]; NSError *error; BOOL success = [[BGTaskScheduler sharedScheduler] submitTaskRequest:request error:&error]; if (success == TRUE) { } } //BREAKPOINT } -(void)handleAppRefreshTask:(BGAppRefreshTask *)task API_AVAILABLE(ios(13.0)){ //do things with task NSLog(@"Process started!"); task.expirationHandler = ^{ NSLog(@"WARNING: expired before finish was executed."); }; MQTTCFSocketTransport *transport = [[MQTTCFSocketTransport alloc] init]; transport.host = @"io.adafruit.com"; transport.port = 1883; self.session3 = [[MQTTSession alloc] init]; self.session3.userName = self.myUserName; self.session3.password = self.myUserKey; self.session3.transport = transport; self.session3.delegate = self; self.session3.keepAliveInterval = 30; // new stuff NSString *feeds = [self.myUserName stringByAppendingString:@"/feeds/"]; self.atrip = [feeds stringByAppendingString:@"trip"]; self.gettrip = [self.atrip stringByAppendingString:@"/get"]; [session3 connectWithConnectHandler:^(NSError *error) { if(!error){ [self.session3 subscribeToTopic:self.atrip atLevel:1 subscribeHandler:^(NSError *error, NSArray *gQoss){ if (error) { NSLog(@"Subscription failed %@", error.localizedDescription); } else { NSLog(@"Subscription sucessfull! Granted Qos: %@", gQoss); NSData* data = [@"0" dataUsingEncoding:NSUTF8StringEncoding]; [self.session3 publishData:data onTopic:self.gettrip retain:NO qos:0 publishHandler:nil]; } }]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(45* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [task setTaskCompletedWithSuccess:YES]; }); self.session3.keepAliveInterval =30; } else {NSLog(@"[connectWithConnectHandler]Error Connect %@", error.localizedDescription);} }]; task.expirationHandler = ^{ NSLog(@"WARNING: expired before finish was executed."); }; } } } //More code here but too much. @end I am not sure about the local notification because the BGAppRefreshTask is not working. I have placed a breakpoint just after the app enters background and the TASK is submitted. Then I type in e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"LEVELIT.refresh"] The app launches in the background but I get an error error: Header search couldn't locate module MQTTClient error: couldn't install checkers, unknown error Message from debugger: Terminated due to signal 9 When I tried running the app without .xcworkspace the project said it couldn't find MQTTClient. But with the workspace everything works fine. Why would launching the app in the background cause the app not to locate the MQTTClient libraries? And how do I work around this problem? Any and all help would be appreciated.
Posted
by gbenna.
Last updated
.
Post not yet marked as solved
2 Replies
240 Views
Configuration: I have a NSTextField (multiline) inside an NSWindow. I have another NSTextField (single line) inside an NSBox (which is in the same window). The multiline text field is first responder and is editing. I click on the single line text field inside the NSBox to edit that one. The NSWindow just closes. This is on Sonoma 14.2.1. I subclassed NSWindow and override the close method and put a breakpoint. Here's the call stack that leads to the window suddenly closing: #1 0x0000000189c73d90 in -[NSWindow __close] () #2 0x000000032343 in -[NSApplication(NSResponder) sendAction:to:from:] () #3 0x0000000189b543ac in -[NSControl sendAction:to:] () #4 0x0000000189b542f0 in __26-[NSCell _sendActionFrom:]_block_invoke () #5 0x0000000189b54218 in -[NSCell _sendActionFrom:] () #6 0x0000000189b5413c in -[NSButtonCell _sendActionFrom:] () #7 0x0000000189c4c508 in __29-[NSButtonCell performClick:]_block_invoke () #8 0x0000000189c4c264 in -[NSButtonCell performClick:] () #9 0x0000000189b545a8 in -[NSApplication(NSResponder) sendAction:to:from:] () #10 0x0000000189b543ac in -[NSControl sendAction:to:] () #11 0x0000000189befb48 in -[NSTextField textDidEndEditing:] () #12 0x0000000__CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ () #13 0x000000018625c65c in ___CFXRegistrationPost_block_invoke () #14 0x000000018625c5a4 in _CFXRegistrationPost () #15 0x00000001861971dc in _CFXNotificationPost () #16 0x0000000187289ff0 in -[NSNotificationCenter postNotificationName:object:userInfo:] () #17 0x0000000189bef754 in -[NSTextView(NSSharing) resignFirstResponder] () #18 0x0000000189a9fab8 in -[NSWindow _realMakeFirstResponder:] () #19 0x0000000189b4f18c in -[NSWindow(NSEventRouting) _handleMouseDownEvent:isDelayedEvent:] () #20 0x0000000189ada79c in -[NSWindow(NSEventRouting) _reallySendEvent:isDelayedEvent:] () #21 0x0000000189ada45c in -[NSWindow(NSEventRouting) sendEvent:] () #22 0x000000018a1879f4 in -[NSApplication(NSEventRouting) sendEvent:] () #23 0x0000000189dd6908 in -[NSApplication _handleEvent:] () #24 0x00000001899a1d74 in -[NSApplication run] () The mouse click is no where near the close button in the title bar.
Posted Last updated
.
Post not yet marked as solved
1 Replies
271 Views
Im honestly a bit lost and looking for general pointers. Here is the general flow of my project. I have an Xcode project where I want to return and convert the temperature values accessed from the apple smc and I found a GitHub repo with all the smc key sensors for the M3Pros/Max chips: https://github.com/exelban/stats/issues/1703 basically, I have all these keys stored in an array in obj-c like so: NSArray *smcKeys = @[ @"Tp01", @"Tp05", @"Tp09", @"Tp0D", @"Tp0b", @"Tp0f", @"Tp0j", @"Tp0n",@"Tp0h", @"Tp0L", @"Tp0S", @"Tp0V", @"Tp0z", @"Tp0v", @"Tp17", @"Tp1F", @"Tp1J", @"Tp1p", @"Tp1h", @"Tp1R", ]; I am passing all these keys by passing 'smcKeys' in a regular C code file I have here that is meant to open, close and read the data shown here: #include "smc.h" #include <mach/mach.h> #include <IOKit/IOKitLib.h> #include "smckeys.h" io_connect_t conn; kern_return_t openSMC(void) { kern_return_t result; kern_return_t service; io_iterator_t iterator; service = IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("AppleSMC"), &iterator); if(service == 0) { printf("error: could not match dictionary"); return 0; } result = IOServiceOpen(service, mach_task_self(), 0, &conn); IOObjectRelease(service); return 0; } kern_return_t closeSMC(void) { return IOServiceClose(conn); } kern_return_t readSMC(char *smcKeys, SMCVal_t *val) { kern_return_t result; uint32_t keyCode = *(uint32_t *)smcKeys; SMCVal_t inputStruct; SMCVal_t outputStruct; inputStruct.datasize = sizeof(SMCVal_t); inputStruct.datatype = 'I' << 24; //a left shift operation. turning the I into an int by shifting the ASCII value 24 bits to the left inputStruct.data[0] = keyCode; result = IOConnectCallStructMethod(conn, 5, &inputStruct, sizeof(SMCVal_t), &outputStruct, (size_t*)&inputStruct.datasize); if (result == kIOReturnSuccess) { if (val -> datasize > 0) { if (val -> datatype == ('f' << 24 | 'l' << 16 | 't' << 8 )) { //bit shifting to from 32bit operation associated with the ASCII charecters'f', 'l', and 't', sets datatype field. double temp = *(double *)val -> data; return temp; } } } return 0.0; } Which I am then then calling the functions from this file in a swift file and converting the values to Fahrenheit but no data is being printed in my console: import IOKit public class getTemperature { public struct SMCVal_t { var datasize: UInt32 var datatype: UInt32 var data: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) } @_silgen_name("openSMC") func openSMC() -> kern_return_t @_silgen_name("closeSMC") func closeSMC() -> kern_return_t @_silgen_name("readSMC") func readSMC(key: UnsafePointer<CChar>?,val: UnsafeMutablePointer<SMCVal_t>) -> kern_return_t func convertAndPrintTempValue(key:UnsafePointer<CChar>?,scale: Character, showTemp: Bool ) -> kern_return_t { let openSM = openSMC() guard openSM == 0 else { print("Failed to open SMC: \(openSM)") return kern_return_t() } let closeSM = closeSMC() guard closeSM == 0 else { print("could not close SMC: \(closeSM)") return IOServiceClose(conn) } func convertAndPrint(val: SMCVal_t) -> Double { if val.datatype == (UInt32("f".utf8.first!) << 24 | UInt32("l".utf8.first!) << 16 | UInt32("t".utf8.first!) << 8) { let extractedTemp = Double(val.data.0) return( extractedTemp * 9.0 / 5.0 + 32.0 ) } return 0.0 } let smcValue = SMCVal_t(datasize: 0, datatype: 0, data: (0,0,0,0,0,0,0,0)) let convertedVal = convertAndPrint(val: smcValue) print("Temperarure:\(convertedVal)F°") return kern_return_t() } } I know this is a lot but I am honestly looking for any tips to fill in any gaps in my knowledge for anyone who's built a similar application meant to extract any sort of data from Mac hardware.
Posted
by Aor1105.
Last updated
.
Post not yet marked as solved
1 Replies
269 Views
I have a sandboxed app in /Applications. I'm attempting to shoot a problem with LLDB, so I cd to /Applications/app-name/Contents/MacOS and do lldb programname. However, once I fire it off with "r" it dies instantly with: error: process exited with status -1 (lost connection) Should this work? Should I try signing the lldb executable? Thanks!
Posted Last updated
.
Post not yet marked as solved
2 Replies
306 Views
Because my MacOS app has a user-programmable interface, my coding creates lots of interface elements programmatically. Soon after an update to MacOS 14.3.1, I found some of these element (NSTextFields) did not draw correctly. I had not changed any code but the appearance changed for the worse (the text in the text field did not appear). I then noticed: The problem occurs when I compile in XCode 15.2 (15C500b) Version and run on computer with Sonoma 14.3.1 (23D60) If I instead compile in XCode Version 14.1 (14B47b) on Ventura 13.0.1 (22A400) and copy the app to my computer with Sonoma 14.3.1 (23D60)all works as expected. These results seem to imply XCode 15.2 does not compile correctly? Is this known issue or is there a fix?
Posted Last updated
.
Post not yet marked as solved
0 Replies
237 Views
Hi there, i have an macOS app, sandboxed, compatibility 10.13 up to Sonoma, objective-C. I have a dropzone (or alternatively selection with NSOpenPanel) where users can drop files which results in an array of NSURLs. I create bookmarks to securely access them. This worked for years. Now i want to add iCloud support. Everything works good so far. I have methods to check the file status and download the file from icloud if NSURLUbiquitousItemDownloadingStatusKey == NSURLUbiquitousItemDownloadingStatusNotDownloaded Then i listen for the file, once the status key changes to NSURLUbiquitousItemDownloadingStatusCurrent i continue with processing the NSURL and i want to create bookmarkData: [filePathUrl bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&amp;error]]; But this returns the error "Could not open() the item: [1: Operation not permitted]" So i was wondering if downloading the file from iCloud now changed the NSURL itself so the given permissions by dropping do not match the downloaded file? Adding [filePathUrl startAccessingSecurityScopedResource]; didn't change anything. Any help appreciated
Posted
by patMorita.
Last updated
.
Post not yet marked as solved
1 Replies
224 Views
I have multiple mobile applications, one developed in React Native and the other in Objective-C and Swift hybrid technology. I use my own system to send push notifications, and these notifications are left encrypted in the Apple queues. However, in any of my applications, I am unable to catch these messages in the code block where I decrypt them. As a result, users see the messages encrypted. While I can deterministically detect this issue on devices experiencing the offload feature from Apple, I've also noticed sporadic occurrences of this issue on devices not utilizing offload. Due to my security policies, I have no chance of sending messages unencrypted. I'm trying to understand why this is happening and need suggestions for a solution. Is there anyone who can help? Additional Information: I use my own system for push notifications. Messages are left encrypted in the Apple queues. I am unable to catch the messages in the code block where I decrypt them in one of the applications. I can deterministically detect the issue on devices experiencing the offload feature. I've noticed sporadic occurrences of this issue on devices not using offload. Due to security policies, I have no chance of sending messages unencrypted. I tried sending without offloading, and the messages arrived unencrypted I searched for a callback handler function on the Apple side - couldn't find one. To ensure notifications were sent correctly, I performed token checks in my database.
Posted Last updated
.
Post not yet marked as solved
0 Replies
291 Views
I have an Xcode project with an obj-c .c file and a .h file aswell as a .swift file where I am calling functions from those obj-c files with a bridging header but when I build my project I get a duplicate symbols error and Xcode doesn't show where. here is .h header file: #define smc_h #include &lt;stdint.h&gt; #include &lt;mach/mach.h&gt; #include &lt;IOKit/IOKitLib.h&gt; typedef struct { uint32_t datasize; uint32_t datatype; uint8_t data[8]; } SMCVal_t; io_connect_t conn; kern_return_t openSMC(void); kern_return_t closeSMC(void); kern_return_t readSMC(char *key, SMCVal_t *val); double convertToFahrenheit(SMCVal_t *val); #endif /* smc_h */ my .c implementation file: #include "smc.h" kern_return_t openSMC(void) { kern_return_t result; kern_return_t service; io_iterator_t iterator; service = IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("AppleSMC"), &amp;iterator); if(service == 0) { printf("error: could not match dictionary"); return 0; } result = IOServiceOpen(service, mach_task_self(), 0, &amp;conn); IOObjectRelease(service); return 0; } kern_return_t closeSMC(void) { return IOServiceClose(conn); } kern_return_t readSMC(char *key, SMCVal_t *val) { kern_return_t result; uint32_t keyCode = *(uint32_t *)key; SMCVal_t inputStruct; SMCVal_t outputStruct; inputStruct.datasize = sizeof(SMCVal_t); inputStruct.datatype = 'I' &lt;&lt; 24; //a left shift operation. turning the I into an int by shifting the ASCII value 24 bits to the left inputStruct.data[0] = keyCode; result = IOConnectCallStructMethod(conn, 5, &amp;inputStruct, sizeof(SMCVal_t), &amp;outputStruct, (size_t*)&amp;inputStruct.datasize); if (result == kIOReturnSuccess) { if (val -&gt; datasize &gt; 0) { if (val -&gt; datatype == ('f' &lt;&lt; 24 | 'l' &lt;&lt; 16 | 't' &lt;&lt; 8 )) { //bit shifting to from 32bit operation associated with the ASCII charecters'f', 'l', and 't', sets datatype field. double temp = *(double *)val -&gt; data; return temp; } } } return 0.0; } double convertToFahrenheit(SMCVal_t *val) { if(val -&gt; datatype == ('f' &lt;&lt; 24 | 'l' &lt;&lt; 16 | 't' &lt;&lt; 8 )) { //checking if val-&gt;datatype is equal to the result of the bit-shifting operation. double temp = *(double *)val -&gt; data; return (temp * 9.0 / 5.0) + 32.0; } return 0.0; } And my .swift file where my objc functions are called: import IOKit public class CPUTempCaller { public struct SMCVal_t { var datasize: UInt32 var datatype: UInt32 var data: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) } @_silgen_name("openSMC") func openSMC() -&gt; Int32 @_silgen_name("closeSMC") func closeSMC() -&gt; Int32 @_silgen_name("readSMC") func readSMC(key: UnsafePointer&lt;CChar&gt;?,val: UnsafeMutablePointer&lt;SMCVal_t&gt;) -&gt; kern_return_t @_silgen_name("convertToFahrenheit") func convertToFahrenheit(val: UnsafePointer&lt;SMCVal_t&gt;) -&gt; Double { let openSM = openSMC() guard openSM == 0 else { print("Failed to open SMC: \(openSM)") return 0.0; } let closeSM = closeSMC() guard closeSM == 0 else { print("could not close SMC: \(closeSM)") return 0.0; } func convertAndPrintTempValue(key:UnsafePointer&lt;CChar&gt;?,scale: Character, showTemp: Bool ) -&gt; Double? { var SMCValue = SMCVal_t(datasize: 0, datatype: 0, data:(0,0,0,0,0,0,0,0)) //initializing SMC value if let Key = key { //check if nil. If not nil, proceed to code block execution let key = "TC0P" let keyCString = (key as NSString).utf8String //passing key as null terminated utf8 string let readSMCResult = readSMC(key: keyCString, val: &amp;SMCValue) //call readSMC obj-C function, store result in "readSMCResult" if readSMCResult != KERN_SUCCESS { print("Failed to read SMC: \(readSMCResult)") } } if showTemp { //return nil if showTemp is false let convertRawToFahrenheit = convertToFahrenheit(val: &amp;SMCValue) let scaleToStr = String(scale) print(String(format: "Temperature: %0.1f °%c", convertRawToFahrenheit, scaleToStr)) return nil } else { print("could not convert temperature and format values in Fahrenheit") return nil } } return 0.0; } }
Posted
by Aor1105.
Last updated
.
Post not yet marked as solved
1 Replies
236 Views
Hi, i have a daemon service written in Objective-C and C++. i need to detect user change events and reboot my service. I'm using SCDynamicStoreKeyCreateConsoleUser and get notifications for user switch events but not for fast user switch events. is there a way to reliably subscribe to all kinds of user switch events including VNC connection?
Posted
by alzix.
Last updated
.
Post not yet marked as solved
1 Replies
260 Views
I have a swift file where I am calling objective c functions and providing pointers to certain values where needed but im getting the error " : Cannot convert value of type 'Swift.UnsafeMutablePointer<MacStat.SMCVal_t>' to expected argument type 'Swift.UnsafeMutablePointer<__ObjC.SMCVal_t>' " Here is the relevant code block where I am getting the error: var convertRawToFahrenheit: Double = 0.0 withUnsafeMutablePointer(to: &SMCValue) { pointer in convertRawToFahrenheit = convertToFahrenheit(val: pointer) } print(String(format: "Temperature: %0.1f °%c", convertRawToFahrenheit )) return nil } else { print("could not convert temperature and format values in Fahrenheit") return nil } return 0.0; } I already have a bridging header and the path to that header set up so I know the issue Isn't anything that involves my C functions not getting recognized in swift. I will also provide my full code: import IOKit public struct SMCVal_t { var datasize: UInt32 var datatype: UInt32 var data: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) } @_silgen_name("openSMC") func openSMC() -> Int32 @_silgen_name("closeSMC") func closeSMC() -> Int32 @_silgen_name("readSMC") func readSMC(key: UnsafePointer<CChar>?,val: UnsafeMutablePointer<SMCVal_t>) -> kern_return_t func convertAndPrintTempValue(key:UnsafePointer<CChar>?,scale: Character, showTemp: Bool ) -> Double? { let openSM = openSMC() guard openSM == 0 else { print("Failed to open SMC: \(openSM)") return 0.0; } let closeSM = closeSMC() guard closeSM == 0 else { print("could not close SMC: \(closeSM)") return 0.0; } var SMCValue = SMCVal_t(datasize: 0, datatype: 0, data:(0,0,0,0,0,0,0,0)) //initializing SMC value if let key = key { //check if nil. If not nil, proceed to code block execution let key = "TC0P" let keyCString = (key as NSString).utf8String //passing key as null terminated utf8 string let readSMCResult = readSMC(key: keyCString, val: &SMCValue) //call readSMC obj-C function, store result in "readSMCResult" if readSMCResult != KERN_SUCCESS { print("Failed to read SMC: \(readSMCResult)") } } if showTemp { //return nil if showTemp is false var convertRawToFahrenheit: Double = 0.0 withUnsafeMutablePointer(to: &SMCValue) { pointer in convertRawToFahrenheit = convertToFahrenheit(val: pointer) } print(String(format: "Temperature: %0.1f °%c", convertRawToFahrenheit )) return nil } else { print("could not convert temperature and format values in Fahrenheit") return nil } return 0.0; }
Posted
by Aor1105.
Last updated
.