开发者

Change a relative URL to absolute URL in Objective C

H开发者_StackOverflow社区ow would I take a file in the application's directory (the same folder the .app is in), and get it's absolute path. Say the relative path is "Data/file.txt," how would I use Objective C to get that as an absolute path? I have the user enter their home folder name, if that is any help.

Please help,

HiGuy


I'd use the NSURL methods that resolve URLs for me, like so:

NSURL * bundle = [[NSBundle mainBundle] bundleURL];
NSURL * file = [NSURL URLWithString:@"../Data/file.txt" relativeToURL:bundle];
NSURL * absoluteFile = [file absoluteURL];

The "../" is necessary, because otherwise it'd try to locate the file inside your app bundle. Putting the "../" beforehand will tell it to look in the bundle's containing folder, and not in the bundle itself. Also, -[NSBundle bundleURL] is a 10.6+ API, but it's trivial to replicate the functionality using an NSURL convenience method and -[NSBundle bundlePath].


Find the location of the running app by doing :

NSString * applicationPath = [[NSBundle mainBundle] bundlePath];

Which will return something like :

/Users/myUser/Library/Application Support/iPhone Simulator/User/Applications/317CF5C7-57B3-42CE-8DF4-4DD10B070D95/Assignment1a.app

Then use - (NSString *)stringByDeletingLastPathComponent to chop off the last bit.


You should just be able to concatenate the root folder of the app, with the relative path. You can get at the app home directory with NSHomeDirectory(), so to get the absolute path you can do something like the following:

NSString *path = [NSHomeDirectory() stringByAppendingString: @"/Data/file.txt"];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜