Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Local file using NSURL

Tags:

ios

iphone

I am trying to access an XML file store in the resources directory. I am using NSURL to access this file using NSURLConnection( this file is going to be swapped out for a remote service in the future).

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"); } 

The class that starts the connection implements the NSURLConnection methods:

connection:willCacheResponse:  connection:didReceiveData:  connectionDidFinishLoading:  connectionDidFinishLoading: 

Once I launch this the simulator dies, no messages are printed to the console so I am at a loss for where to look. Any ideas, or am I just doing this completely wrong?

like image 382
botptr Avatar asked Feb 10 '11 17:02

botptr


People also ask

What is a Nsurl?

An object representing the location of a resource that bridges to URL ; use NSURL when you need reference semantics or other Foundation-specific behavior. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+

What is a NS URL?

The NSURL class is a subclass of the NSObject class and it provides methods for creating and manipulating URL addresses. URL stands for “Universal Resource Locator”. Here are few things you should know about the NSURL class: It is the only class spelt with all upper case.


2 Answers

Trying to load anything from the filesystem root is wrong, wrong, wrong. Definitely wrong on the device, and probably wrong on the simulator. The resources directory should be accessed via the NSBundle class.

For example, to get a URL for a file called "Data.txt" in the resources, use the following:

NSURL *MyURL = [[NSBundle mainBundle]     URLForResource: @"Data" withExtension:@"txt"]; 
like image 136
Seva Alekseyev Avatar answered Oct 01 '22 01:10

Seva Alekseyev


If you want to get a URL from a path (say, because you created a file in NSTemporaryDirectory() and you need to get that as a URL) you can easily do so by using NSURL's fileURLWithPath method:

NSString* tempPath = NSTemporaryDirectory(); NSString* tempFile = [tempPath stringByAppendingPathComponent:fileName]; NSURL* URL = [NSURL fileURLWithPath:tempFile]; 

Much easier than +URLWithString: and other methods.

like image 29
Andres Kievsky Avatar answered Oct 01 '22 00:10

Andres Kievsky