带字符串的NSURL给出null值

时间:2013-05-21 10:17:50

标签: objective-c url ios6 nsurl file-exists

以下是我的内容

NSString *foofile = @"/Users/alkandari/Library/Application Support/iPhone Simulator/6.1/Applications/8C445026-6387-4E40-B5A3-D1A1680666D6/Documents/ProjacsBODFiles/file_5_21.pdf"
NSURL *url;
if (fileExists) {
    url = [NSURL URLWithString:foofile];
    NSLog(@"taking local file 1 ... %@==%@", url, foofile);
} else {

    url=[NSURL URLWithString:address];
    NSLog(@"taking internet file 1... %@", url);
}

当我执行时,我得到如下的日志

taking local file 1 ... (null)==/Users/alkandari/Library/Application Support/iPhone Simulator/6.1/Applications/8C445026-6387-4E40-B5A3-D1A1680666D6/Documents/ProjacsBODFiles/file_5_21.pdf

我不明白为什么我将URL设为null。因此,我无法打开文件。

我知道为什么我上面的URL为空?

2 个答案:

答案 0 :(得分:1)

您需要使用fileURLWithPath作为本地文件系统的路径:

NSString *foofile = @"/Users/alkandari/Library/Application Support/iPhone Simulator/6.1/Applications/8C445026-6387-4E40-B5A3-D1A1680666D6/Documents/ProjacsBODFiles/file_5_21.pdf"
NSURL *url;
if (fileExists) {
    url = [NSURL fileURLWithPath:foofile];
    NSLog(@"taking local file 1 ... %@==%@", url, foofile);
} else {
...
}

答案 1 :(得分:1)

您还可以使用以下代码访问模拟器文件夹中的文件;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *libraryBaseDirectory = [paths objectAtIndex:0];

NSString *privateDocumentsDirectory = [libraryBaseDirectory stringByAppendingPathComponent:@"ProjacsBODFiles"];