NSData not accepting escaped / UTF8 encoded URL - ios

I am trying to create an NSData object that contains the contents of a file in my main bundle.
NSString *chordPath = [[NSBundle mainBundle] pathForResource:chordName ofType:#"png"];
NSURL *chordURL = [NSURL URLWithString:[chordPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *chordImageData = [NSData dataWithContentsOfURL:chordURL];
UIImage *chordImage = [UIImage imageWithData:chordImageData];
Prior to using stringByAddingPercentEscapesUsingEncoding I was getting a nil URL, so I went ahead and fixed that by reencoding the string. Now I get a valid URL but the chordImageData object is nil for me. The file is definitely included in my main bundle (since I was able to get the URL to begin with) so I am wondering what's wrong.
EDIT:
Running this:
NSData *chordImageData = [NSData dataWithContentsOfURL:chordURL options:NSDataReadingMapped error:&dataCreationError];
Gets me this for the error:
po dataCreationError
Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0x7530a00
Looking around Google it seems that the URL is still not encoded correctly. Anyone know an additional step to make sure the encoding is valid?

Try using fileURLWithPath:, something like this:
NSString *chordPath = [[NSBundle mainBundle] pathForResource:chordName ofType:#"png"];
NSURL *chordURL = [NSURL fileURLWithPath: chordPath];
NSData *chordImageData = [NSData dataWithContentsOfURL:chordURL];
UIImage *chordImage = [UIImage imageWithData:chordImageData];

There should be no need to do percent escaping. The reason you're having problems is that you are using URLWithString: which is meant for "non-file" URLs.
You should use +fileURLWithPath: for file-based URLs:
NSString *chordPath = [[NSBundle mainBundle] pathForResource:chordName ofType:#"png"];
NSURL *chordURL = [NSURL fileURLWithPath:chordPath];
NSData *chordImageData = [NSData dataWithContentsOfURL:chordURL];
UIImage *chordImage = [UIImage imageWithData:chordImageData];

Related

imageWithcontentsOfFile failing to load saved image from simulator cache dir

I'm writing an image to the simulators cache directory using
NSURL *cacheDir = [[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory
inDomains:NSUserDomainMask].lastObject;
NSURL *avatarFileURL = [cacheDir URLByAppendingPathComponent:#"test.png" isDirectory:NO];
NSData *imageData = UIImagePNGRepresentation(avatarImage);
[imageData writeToURL:avatarFileURL atomically:YES];
This works fine and I've verified the image by logging the avatarFile url and loading it into a browser, which displays the cache image.
I then try and read the test image back and I'm getting different results if I use imageWithContentsOfFile: and imageWithData: as follows:
NSURL *cacheDir = [[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory
inDomains:NSUserDomainMask].lastObject;
NSURL *avatarFileURL = [cacheDir URLByAppendingPathComponent:#"test.png" isDirectory:NO];
// Returns a nil.
NSString *avatarFile = avatarFileUrl.absoluteString;
UIImage *image1 = [UIImage imageWithContentsOfFile:avatarFile];
// Returns the image.
NSData *imageData = [NSData dataWithContentsOfURL:avatarFileUrl];
UIImage *image2 = [UIImage imageWithData:imageData];
I'm at a loss to explain why imageWithContentsOfFile fails and imageWithData works when they are both addressing the same URL. I've verified the URL by logging it and urls are exactly the same.
Anyone know why imageWithContentsOfFile is not working?
Your issue is with this line:
NSString *avatarFile = avatarFileUrl.absoluteString;
Look at the value of avatarFile. It will be something like file:///..... imageWithContentsOfFile: expects a proper file path, not a file URL.
You need to properly convert the file URL into a path. That is done as follows:
NSString *avatarFile = avatarFileUrl.path;

NSURL URLWithString returns nil

I am stuck in a very obvious method of NSURL class URLWithString I am passing a string and while creating URL it returns nil, my string is perfect. When ever I uses same string in browser then it is working fine. I am using following method to convert NSString to NSURL:
NSURL *url = [NSURL URLWithString:urlString];
//urlString is my perfect string
I have also tried to encode my string first by using following
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// using this line my output string when I log url is "url%10%10%10%10%10%10..."
%10 becomes the suffix of my url with around 100+ repetition.
If any one has idea what %10 is or what can be done to overcome this problem.
here is my urlString:
Use below code to resolve your problem.
NSString *str = msgDetail[#"thumbnail"];
NSString* webStringURL = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL* url = [NSURL URLWithString:webStringURL];
yes what was wrong in my string were many unidentified characters due to copying from internet site, if anyone of the reader facing this issue can copy and paste your string as see the count. And confirm.
Thanks
Try below solution
NSURL *url = [NSURL URLWithString:[urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Check it..!

IOS - can't load image at root of app

I'm new to iOS and need to create a NSURL that points to an image that I have copied into the root of my application (i.e. same directory as the AppDelegate & my controller class files reside).
Giving the following code, why does the image not load & how can I get the if condition to validate (i.e. have a NSURL reference to my image)?
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *image2AbsolutPath = [mainBundle pathForResource:#"image2" ofType:#"jpg"];
NSURL *urlToImage = [NSURL URLWithString:image2AbsolutPath];
NSError *error = nil;
if (![urlToImage checkResourceIsReachableAndReturnError:&error]) {
NSLog(#"image2.jpg could not be reached.");
}
Edit: As per the comment; created an imageview and successfully loaded and viewed the image via; self.imageView.image=[UIImage imageNamed:#"image2.jpg"];
Only the NSURL loading seems to not work.
you mixup URLWithString and fileURLWithPath
//wrong
NSString *image2AbsolutPath = [mainBundle pathForResource:#"image2" ofType:#"jpg"];
NSURL *urlToImage = [NSURL URLWithString:image2AbsolutPath];
you use the former but pass it NOT a url string BUT a file path. Change to the latter and it would work
//works
NSString *image2AbsolutPath = [mainBundle pathForResource:#"image2" ofType:#"jpg"];
NSURL *urlToImage = [NSURL fileURLWithPath:image2AbsolutPath];
//but more simply
NSURL *urlToImage = [mainBundle URLForResource:#"image2" withExtension:#"jpg"];
To load the resource you need to use
NSURL *url = [[NSBundle mainBundle] URLForResource: #"image2" withExtension:#"jpg"];
If you look at the two different paths created with pathForResource vs the URLForResource method you will see the NSURL path is missing the required file://
pathForResource:
/Users/MacbookPro/Library/Developer/CoreSimulator/Devices/02D50AC9-5AF0-4F23-8757-1AF7D3153344/data/Containers/Bundle/Application/C5775786-E473-4048-9855-A2C6AA51BB05/MyApp.app/image2.png
vs
URLForResource:
file:///Users/MacbookPro/Library/Developer/CoreSimulator/Devices/02D50AC9-5AF0-4F23-8757-1AF7D3153344/data/Containers/Bundle/Application/C5775786-E473-4048-9855-A2C6AA51BB05/MyApp.app/image2.png

+URLWithString: returns nil

Im using QLPreviewController to view word, excel,pdf etc. The problem is the file is in the server so I need to download it from a certain URL.
I'm using this code:
NSURL *dLurl = [NSURL URLWithString:[NSString stringWithFormat:#"%#",DLPathStr]];
NSData *data = [NSData dataWithContentsOfURL:dLurl];
for downloading files, It works for the PDF file but in the word and excel files it doesn't work I'm not able to download anything.
I fixed it by using this code it doesn't download anything because the URL is wrong because it contains spaces.
NSString *str = [DLPathStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *dLurl = [NSURL URLWithString:[NSString stringWithFormat:#"%#",str]];

Extracting data from an audio file

We have a web services function to which we are uploading an audio file into to be saved in the server. The code that I am using to create a data buffer (to pass to the web services) of the contents of the audio file is :
NSURL *soundFileURL = [[NSURL alloc] initFileURLWithPath:fnWithSlash];
audioData = [NSData dataWithContentsOfURL:soundFileURL];
NSLog(#"audiodata%d",audioData.length);
Here fnWithSlash contains the full path of the file. However audioData.length is always 0.
What am i missing?
Thanks in advance for your response.
Try using NSData's dataWithContentsOfFile: instead..If the file is in your bundle it will look like the example below, otherwise construct the filePath of the sound file to your desired location..
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"yourSound" ofType:#"wav"];
audioData = [NSData dataWithContentsOfFile:filePath];
NSLog(#"audiodata%d",audioData.length);

Resources