xcode 在 Objective C 中将相对 URL 更改为绝对 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2123725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:04:59  来源:igfitidea点击:

Change a relative URL to absolute URL in Objective C

objective-cxcodeurlrelative-pathabsolute-path

提问by Glenn Smith

How 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.

我将如何获取应用程序目录中的文件(.app 所在的文件夹),并获取它的绝对路径。假设相对路径是“Data/file.txt”,我将如何使用 Objective C 将其作为绝对路径?如果有帮助,我让用户输入他们的主文件夹名称。

Please help,

请帮忙,

HiGuy

嗨帅哥

采纳答案by Tyr

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 *)stringByDeletingLastPathComponentto chop off the last bit.

然后- (NSString *)stringByDeletingLastPathComponent用来切掉最后一点。

回答by Dave DeLong

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

我会使用NSURL为我解析 URL的方法,如下所示:

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 insideyour 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 NSURLconvenience method and -[NSBundle bundlePath].

“../”是必要的,否则它会尝试您的应用程序包中定位文件。预先放置“../”将告诉它查看包的包含文件夹,而不是包本身。此外,它-[NSBundle bundleURL]是一个 10.6+ API,但NSURL使用方便的方法和-[NSBundle bundlePath].

回答by Tom Jefferys

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:

您应该能够将应用程序的根文件夹与相对路径连接起来。您可以使用 NSHomeDirectory() 获取应用程序主目录,因此要获取绝对路径,您可以执行以下操作:

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