使用NSURL访问本地文件

bot*_*ptr 48 iphone ios

我试图访问资源目录中的XML文件存储.我正在使用NSURL使用NSURLConnection访问此文件(此文件将来将被替换为远程服务).

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL 
URLWithString:@"file:///XMLTest.xml"] 
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
    // Create the NSMutableData to hold the received data.
    // receivedData is an instance variable declared elsewhere.
    response = [[NSMutableData data] retain];
} else {
    NSLog(@"Could not create connection");
}
Run Code Online (Sandbox Code Playgroud)

启动连接的类实现NSURLConnection方法:

connection:willCacheResponse: 
connection:didReceiveData: 
connectionDidFinishLoading: 
connectionDidFinishLoading:
Run Code Online (Sandbox Code Playgroud)

一旦我启动它,模拟器就会死机,没有消息打印到控制台,所以我不知道在哪里看.任何想法,或者我只是这样做完全错了?

Sev*_*yev 157

试图从文件系统加载任何东西是错误的,错误的,错误的.在设备上肯定是错误的,并且在模拟器上可能是错误的.应该通过NSBundle类访问资源目录.

例如,要获取资源中名为"Data.txt"的文件的URL,请使用以下命令:

NSURL *MyURL = [[NSBundle mainBundle]
    URLForResource: @"Data" withExtension:@"txt"];
Run Code Online (Sandbox Code Playgroud)

  • 我在iOS上的印象'/'访问了应用程序沙箱根,我很容易就会出错.这是我用来获取网址的代码,应用程序仍在爆炸,但这似乎是一个更聪明的举动.`NSURL*url = [[NSBundle mainBundle] URLForResource:@"XMLTest"withExtension:@"xml"];` (2认同)

And*_*sky 31

如果您想从路径中获取URL(例如,因为您在NSTemporaryDirectory()中创建了一个文件,并且需要将其作为URL),可以使用NSURL的fileURLWithPath方法轻松完成:

NSString* tempPath = NSTemporaryDirectory();
NSString* tempFile = [tempPath stringByAppendingPathComponent:fileName];
NSURL* URL = [NSURL fileURLWithPath:tempFile];
Run Code Online (Sandbox Code Playgroud)

比+ URLWithString:和其他方法容易得多.

  • 这是正确的方法,`+ fileURLWithPath:`PUMP UP! (4认同)

Nic*_*ght 19

这也有效:

NSString *path = [[NSBundle mainBundle] pathForResource:@"XMLTest" ofType:@"xml"];
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 虽然我的答案已被标记为正确答案,但我相信Seva的答案实际上是正确的!这可以更新吗? (11认同)