我试图访问资源目录中的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)
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:和其他方法容易得多.
Nic*_*ght 19
这也有效:
NSString *path = [[NSBundle mainBundle] pathForResource:@"XMLTest" ofType:@"xml"];
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
72459 次 |
| 最近记录: |