NSData dataWithContentsOfURL returning nil specifically in iOS 8

3.3k views Asked by At

I am tring to get the NSData from a local file using [NSData dataWithContentsOfURL:] but am getting nil even when the fileSize returned by [NSFileManager defaultManager] is a positive integer.

Surprisingly, I got this issue when the base sdk was increased from iOS 7 to iOS 8.

4

There are 4 answers

0
rahulg On BEST ANSWER

I am not sure whether it is an iOS bug or what as it worked in iOS 7 base SDK and not with iOS 8, but here is the solution I found after wasting a couple of hours debugging the code :-(

Use [NSData dataWithContentsOfFile:(NSString *)] instead of dataWithContentsOfURL

0
ylgwhyh On

NSData and URLs: There be dragons

+[NSData dataWithContentsOfURL:] can return nil for any number of reasons. If anything goes wrong when attempting to use that URL this method will return nil. For example the file may not exist, the network connection may time out, or the URL may even be malformed. nil is returned and the application has no idea why.

+ [NSData dataWithContentsOfURL:options:error:] on the other hand, will tell the caller what went wrong. When nil is returned the error argument will be populated with an object that describes the problem that occured. Using this method would directly answer the question of "why".

Both of these are synchronous methods and their use for working with files, network resources, and especially files served from a network resource is discouraged. These methods will block the caller and are not really intended for these kinds of uses. It's better to use an input stream or NSURLSession instead.

you can reference enter link description here

0
Moose On

Are you sure you pass the Bundle path as well ?

Try with this

NSString* path = [[NSBundle mainBundle].bundlePath stringByAppendingPathComponent:yourPath];
NSData* data = [NSData dataWithContentsOfURL:path];
0
KwanWoo Park On

My case. it had a space in the URL

remove space