开发者

Sending bundled application to Applications folder

I'm trying to move an application that is located in my project bundle to the users Applications folder. The bundled "testApp.app" is located in the projects Resources folder. My code is not getting it done. Is there something wrong开发者_开发百科 with how I am pointing to the global Applications folder on the user's system?

Thanks.

Paul

NSFileManager* fileManager = [NSFileManager defaultManager];

NSError *error = nil;

NSString *appDirectory = [NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *path =  [appDirectory stringByAppendingPathComponent:@"~/Applications/testApp.app"];
[path stringByExpandingTildeInPath];


if ([fileManager fileExistsAtPath:path isDirectory:NULL]) {
[fileManager removeItemAtPath:path error:&error];

}

if(![fileManager fileExistsAtPath:path]){       
}


NSData *data = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/testApp.app"]];
[data writeToFile:path atomically:YES];


.app "files" aren't actually files, they're directories (right click on one and "Show Contents"). Therefore, you need to copy them as such.

There are some other issues with your code as well, the [NSString stringBy...] messages return a new string, since NSString is immutable, so you'll need to assign the return value instead of just passing the message.


Try something like this:

NSString *sourcePath = [[NSBundle mainBundle] 
                    pathForResource:@"testApp" ofType:@"app"];
if (sourcePath == nil) {
    NSLog(@"testApp.app was not found");
    return;
}
NSArray *appsFolders = NSSearchPathForDirectoriesInDomains(
             NSApplicationDirectory, NSUserDomainMask, YES);
if ([appsFolders count] == 0) {
    NSLog(@"~/Applications/ not found");
    return;
}
NSString *appsFolder = [appsFolders objectAtIndex:0];
NSString *destPath = [appsFolder stringByAppendingPathComponent:@"testApp.app"];
NSFileManager *fileManager = [NSFileManager defaultManager];

[fileManager removeItemAtPath:destPath error:&error];

if (![fileManager copyItemAtPath:sourcePath toPath:destPath error:&error]) {
    NSLog(@"failed to copy %@ to %@", sourcePath, destPath);
}

Note that in your code, you had appDirectory set to something that would expand to something like /Users/<username>/Applications, and the following line would have equated to something like this:

NSString *path = [@"/Users/<username>/Applications"
 stringByAppendingPathComponent:@"~/Applications/testApp.app"];

Which is probably not what you wanted.


Andy Kim made his solution (LetsMove) public on GitHub. You can find it here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜