Why is the path of NSApplicationSupportDirectory not the same in Cocoa app and console app? - objective-c

I made a small tool and needed to access the Application Support directory of the user layer, so I created a command line project, used URLsForDirectory to get the path, and everything worked fine.
But when I create a cocoa project with a gui, the path it returns is under the Containers directory, which doesn't seem to exist.
What's causing this discrepancy? What should I do to get the ~/Library/Application Support directory in the cocoa project?
this is the code:
#import "ViewController.h"
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSArray* pathes = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask
];
NSString* applicationSupportPath = [pathes firstObject];
NSLog(#"Application Support:%#\n", applicationSupportPath);
}
- (void)setRepresentedObject:(id)representedObject {
[super setRepresentedObject:representedObject];
// Update the view, if already loaded.
}
#end
the output is :
2022-10-03 22:01:23.230600+0800 TestApplicationSupportPath[49579:213899] Application Support:file:///Users/bodong/Library/Containers/com.bodong.TestApplicationSupportPath/Data/Library/Application%20Support/
console :
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
#autoreleasepool {
// insert code here...
NSLog(#"Hello, World!");
}
NSArray* pathes = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask
];
NSString* applicationSupportPath = [pathes firstObject];
NSLog(#"Application Support:%#\n", applicationSupportPath);
return 0;
}
the output is :
2022-10-03 22:02:09.341780+0800 TestASPCmd[49791:215344] Application Support:file:///Users/bodong/Library/Application%20Support/
Program ended with exit code: 0

I found a solution, just in the project properties, switch to Signing&Capabilities, delete the Sanbox group.

Related

MLKit object detector is crashing in MLKObjectDetectorOptions

I am trying to fetch object frames from given image using MKLKIT. But my code is getting crashed
MLKObjectDetectorOptions *options = [[MLKObjectDetectorOptions alloc] init];
#import <Foundation/Foundation.h>
#import <MLKitObjectDetection/MLKitObjectDetection.h>
#import <MLKitObjectDetectionCommon/MLKObjectDetector.h>
#import <MLKitObjectDetection/MLKObjectDetectorOptions.h>
#import <MLKitObjectDetectionCommon/MLKObject.h>
#import <MLKitVision/MLKVisionImage.h>
#import "MLKitObjectDetection.h"
#implementation MLObjectDetection
- (NSMutableArray*)detectFrame:(UIImage*)image{
NSMutableArray *frames = [NSMutableArray new];
// Multiple object detection in static images
MLKObjectDetectorOptions *options = [[MLKObjectDetectorOptions alloc] init];
options.detectorMode = MLKObjectDetectorModeSingleImage;
options.shouldEnableMultipleObjects = YES;
MLKObjectDetector *objectDetector = [MLKObjectDetector objectDetectorWithOptions:options];
MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image];
visionImage.orientation = image.imageOrientation;
NSError *error;
NSArray *objects = [objectDetector resultsInImage:visionImage error:&error];
if (error == nil) {
return frames;
}
if (objects.count == 0) {
// No objects detected.
}
for (MLKObject *object in objects) {
[frames addObject:[NSValue valueWithCGRect:object.frame]];
}
//TODO release memory
return frames;
}
#end
When your code crash, did you try to run your code inside Xcode and look into the console in the debug area to check what error message was printed out there? Usually that will give you some clue as to what led to the crash.
Based on your code, are you calling the detectFrame: method from the main UI thread? The synchronous MLKObjectDetector#resultsInImage:error: should never be called from the main UI thread. This is documented in its API reference. You can check out ML Kit's quickstart sample app here. It shows how to call both the synchronous MLKObjectDetector#resultsInImage:error: API and the asynchronous MLKObjectDetector#processImage:completion: API.

macOS: Detect all application launches including background apps?

Newbie here. I'm trying to create a small listener for application launches, and I already have this:
// almon.m
#import <Cocoa/Cocoa.h>
#import <stdio.h>
#include <signal.h>
#interface almon: NSObject {}
-(id) init;
-(void) launchedApp: (NSNotification*) notification;
#end
#implementation almon
-(id) init {
NSNotificationCenter * notify
= [[NSWorkspace sharedWorkspace] notificationCenter];
[notify addObserver: self
selector: #selector(launchedApp:)
name: #"NSWorkspaceWillLaunchApplicationNotification"
object: nil
];
fprintf(stderr,"Listening...\n");
[[NSRunLoop currentRunLoop] run];
fprintf(stderr,"Stopping...\n");
return self;
}
-(void) launchedApp: (NSNotification*) notification {
NSDictionary *userInfo = [notification userInfo]; // read full application launch info
NSString* AppPID = [userInfo objectForKey:#"NSApplicationProcessIdentifier"]; // parse for AppPID
int killPID = [AppPID intValue]; // define integer from NSString
kill((killPID), SIGSTOP); // interrupt app launch
NSString* AppPath = [userInfo objectForKey:#"NSApplicationPath"]; // read application path
NSString* AppBundleID = [userInfo objectForKey:#"NSApplicationBundleIdentifier"]; // read BundleID
NSString* AppName = [userInfo objectForKey:#"NSApplicationName"]; // read AppName
NSLog(#":::%#:::%#:::%#:::%#", AppPID, AppPath, AppBundleID, AppName);
}
#end
int main( int argc, char ** argv) {
[[almon alloc] init];
return 0;
}
// build: gcc -Wall almon.m -o almon -lobjc -framework Cocoa
// run: ./almon
Note: when I build it, it will run fine, but if you do it with Xcode 10 on High Sierra, you will get ld warnings, which you can ignore, however.
My question: Is there a way to also detect a launch of a background application, e.g. a menu bar application like Viscosity etc.? Apple says that
the system does not post
[NSWorkspaceWillLaunchApplicationNotification] for background apps or
for apps that have the LSUIElement key in their Info.plist file.
If you want to know when all apps (including background apps) are
launched or terminated, use key-value observing to monitor the value
returned by the runningApplications method.
Here: https://developer.apple.com/documentation/appkit/nsworkspacewilllaunchapplicationnotification?language=objc
I would at least try to add support for background apps etc. to the listener, but I don't know how to go about it. Any ideas?
As the document suggests, you use Key-Value Observing to observe the runningApplications property of the shared workspace object:
static const void *kMyKVOContext = (void*)&kMyKVOContext;
[[NSWorkspace sharedWorkspace] addObserver:self
forKeyPath:#"runningApplications"
options:NSKeyValueObservingOptionNew // maybe | NSKeyValueObservingOptionInitial
context:kMyKVOContext];
Then, you would implement the observation method (using Xcode's ready-made snippet):
- (void) observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context
{
if (context != kMyKVOContext)
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
return;
}
if ([keyPath isEqualToString:#"runningApplications"])
{
<#code to be executed when runningApplications has changed#>
}
}

How to pull data point from Firebase using Obj-C?

I'm saving a users zip code to the Firebase database and want to query that database on app launch to see if the user has input their zip code already or if they're a brand new user.
I've posted my code before. I pulled the sample code from the Firebase docs, but it seems that my app is never even running the following code to get the value
[[[_ref child:#"user"] child:userID] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {...
What am I missing out on?
#import "FollowingVC.h"
#import <FirebaseDatabase/FirebaseDatabase.h>
#import Firebase;
#interface FollowingVC ()
#property NSString *uid;
#property FIRDatabaseReference *ref;
#property NSString *zipcode;
#end
#implementation FollowingVC
- (void)viewDidLoad {
[super viewDidLoad];
[self createAuthorizedUser];
[self checkForZipCode];
}
-(void)createAuthorizedUser
{
[[FIRAuth auth]
signInAnonymouslyWithCompletion:^(FIRUser *_Nullable user, NSError *_Nullable error) {
if (!error) {
self.uid = user.uid;
self.ref=[[FIRDatabase database]reference];
}
}];
}
-(void)checkForZipCode
{
NSString *userID = [FIRAuth auth].currentUser.uid;
[[[_ref child:#"user"] child:userID] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
// Get user value
self.zipcode = snapshot.value[#"zip code"];
NSLog(#"It worked: %#", self.zipcode);
// ...
} withCancelBlock:^(NSError * _Nonnull error) {
NSLog(#"%#", error.localizedDescription);
}];
}
#end
Firebase is asynronous and you need to allow time for events to complete before moving on in the app.
In this case, you should call [self checkForZipCode] inside the sign-in block after self.uid is populated.
Otherwise you run the risk of the checkForZipCode function running before the self.uid is populated.
Let Firebase control the flow of the app - and don't try to use Firebase synchronously as it will get you into trouble due to internet lag etc.

SpriteKit .sks files and subclassing

Apple demoed this code in their WWDC 2014 Session 608 video on best practices for SpriteKit.
AppDelegate.m
+ (instancetype)unarchiveFromFile:(NSString *)file {
/* Retrieve scene file path from the application bundle */
NSString *nodePath = [[NSBundle mainBundle] pathForResource:file ofType:#"sks"];
/* Unarchive the file to an SKScene object */
NSData *data = [NSData dataWithContentsOfFile:nodePath
options:NSDataReadingMappedIfSafe
error:nil];
NSKeyedUnarchiver *arch = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
[arch setClass:self forClassName:#"SKScene"];
SKScene *scene = [arch decodeObjectForKey:NSKeyedArchiveRootObjectKey];
[arch finishDecoding];
return scene;
}
I understand the gist of what it's doing, but what I'm confused about is how to utilize this code in for any other .sks file. I tried calling the unarchiveFromFile method from my GameScene.m class, but to no avail. I read the post here on this topic, but it did not clarify things.
EDIT
As per what was suggested by Okapi, I tried the following in a new OS X SceneKit project in the GameScene.m class:
#import "GameScene.h"
#implementation GameScene
-(void)didMoveToView:(SKView *)view {
SKNode *nodeInScene2 = [self childNodeWithName:#"object1"];
for (SKNode *blah in [SKScene unarchiveFromFile:#"Scene2"].children) {
[nodeInScene2 addChild:blah];
}
}
-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
}
#end
I have 2 .sks files. The first is called GameScene.sks and that has a sprite in there called "object1". I would like to add children stored in "Scene2.sks". The loop in the didMoveToView method gives me an error. What am I doing wrong? This is what Apple did in their WWDC 608 video, but perhaps I'm missing something since I can't find their project online.
+unarchiveFromFile: is defined as a category on SKScene in GameViewController.m. You would need to copy that code if you want to use it somewhere else.
#implementation SKScene (Unarchive)
+ (instancetype)unarchiveFromFile:(NSString *)file {
/* Retrieve scene file path from the application bundle */
NSString *nodePath = [[NSBundle mainBundle] pathForResource:file ofType:#"sks"];
/* Unarchive the file to an SKScene object */
NSData *data = [NSData dataWithContentsOfFile:nodePath
options:NSDataReadingMappedIfSafe
error:nil];
NSKeyedUnarchiver *arch = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
[arch setClass:self forClassName:#"SKScene"];
SKScene *scene = [arch decodeObjectForKey:NSKeyedArchiveRootObjectKey];
[arch finishDecoding];
return scene;
}
#end
This one hung me up for a while too. I ended up declaring unarchiveFromFile in every subclass that needed it, then calling it when I wanted to transition scenes. Something like this...
if (contactQuery == (playerCategory | proceedCategory)) {
SKScene *levelTwo = [LevelTwo unarchiveFromFile:#"LevelTwo"];
[self.view presentScene:levelTwo transition:[SKTransition doorsCloseHorizontalWithDuration:0.5]];
}
Full sample code can be downloaded here.

asyncudpsocket does not send UDP as expected

I have XCODE 3.1.4 running ona mini MAC 10.5.8 and Simulator 3.1
I want to send a short UDP string for some remote control and have made the following code
Basicly it does compile and run in the simulator ... but it nevers send any UDP to the target. I hope someone can give me a clue why it does not work
My .H code
#import <UIKit/UIKit.h>
#import "AsyncUdpSocket.h"
#import "AsyncSocket.h"
#interface ChangeLabelViewController : UIViewController {
IBOutlet UILabel *label ;
AsyncUdpSocket *socket;
}
-(IBAction) ChangeLabel;
-(IBAction) ResetLabel;
#end
My .m code
#import "ChangeLabelViewController.h"
#implementation ChangeLabelViewController
-(IBAction) ChangeLabel
{
label.text = #"Hello";
}
-(IBAction) ResetLabel
{
label.text = #"Empty";
NSLog(#"%s", __PRETTY_FUNCTION__);
NSString * string = #"Testing iPhone";
NSString * address = #"192.168.1.11";
UInt16 port = 1234;
NSData * data = [string dataUsingEncoding: NSUTF8StringEncoding];
if ([socket sendData:data toHost:address port:port withTimeout:- 1 tag:1]) label.text = #"Send";
// if ([socket sendData:data toHost:address port:port withTimeout:-1 tag:1] == YES) label.text = #"Yes";
// if ([socket sendData:data toHost:address port:port withTimeout:-1 tag:1] == NO) then label.text = #"No";
;
}
#end
Had to init the socket
under - (void) vievDidLoad
socket = [[AsyncUdpSocket alloc] initWithDelegate:self];
Then it worked as expected :-)
If you are staring from a brand new project you will also need to do the following:
1. add CFNetwork to your frameworks in the project
2. add the cocaasyncsockets files to your project
Instructions are here: http://code.google.com/p/cocoaasyncsocket/wiki/iPhone
Pay attention to the instructions on how to add CFNetwork, it is not shown in the list of available options.
Hint: you will need to use the finder to select a path, I am a mac novice so it took me a while to figure out that I had to use Go/Go To Folder....