stringWithContentsOfURL returning (null) - ios

I'm trying to convert a URL to a String with the following code:
NSURL *urlOfOpenedFile = _service.myURLRequest.URL;
NSString *fileThatWasOpened = [NSString stringWithContentsOfURL:urlOfOpenedFile encoding:NSASCIIStringEncoding error:nil];
NSLog(#"url: %#", urlOfOpenedFile);
NSLog(#"string: %#", fileThatWasOpened);
This returns:
url: file://localhost/Users/User/Library/Application%2520Support/iPhone%2520Simulator/6.0/Applications/72AA03A1-3967-4F22-9745-0722C8DE9FAC/Documents/downloads/My%20Document%20.pdf
string: (null)
Can anyone tell me how to convert the URL to a string? Thanks.

You can use
NSString* yourURLString = [urlOfOpenedFile absoluteString];

The method you use is not for converting a NSURL to a NSString. Instead like the method name it returns the string from content of that URL. Since you have PDF file (not string) on that URL it returns nil.
For converting you can use the following instance method of NSURL
- (NSString *)absoluteString;

you can use like
NSString *fileThatWasOpened = [NSString stringWithFormat:#"%#", url];

Related

ios, how to create #define for URL that will have dynamic variable in it

I want to create a global variable which is part of a URL, which will be created on run time using a string from the user.
For example:
#define base_URL #"http://api.openweathermap.org/data/2.5/find?q=%#&unit=metrics"
also please suggest how should I use it, for example:
NSString *url = [NSString stringWithFormat:#"%#%#", base_URL, string.text];
You could simply do the following having NSString *input:
NSString *url = [NSString stringWithFormat:base_URL, input];
This will replace %# with the string from input
From my point of view you've got 2 options
Store the variable on a Plist and read it every time you need it
Create a singleton which contains the variable
I'd go with 1, but that's a personal choice
Did you try with this one?
#define BASE_URL(__ARGS__) [NSString stringWithFormat: #"YOUR_URL%#", __ARGS__]
You can use it as:
NSURL *url = [NSURL urlWithString: BASE_URL(string.text)];
You can use the method
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target
withString:(NSString *)replacement
Example
#define URL #"This is %# Url"
NSString *newStr = [URL stringByReplacingOccurrencesOfString:#"%#" withString:#"Hello"];

[__NSCFString absoluteString]: unrecognized selector sent to instance, attempt to convert url to string

Looking to simply convert the parse image url to a string so I can use SDWebImage for caching, etc.
After researching I found that I can convert from a url to string by calling absoluteString on the NSURL. I've also tried this:
NSURL *theUrl = [[obj objectForKey:#"image"] url];
NSString *finalUrl = [theUrl absoluteString];
[cell.carPhoto setImageWithURL:[NSURL URLWithString:finalUrl]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
but I am also crashing on this line with the same error
NSString *finalUrl = [theUrl absoluteString];
Any ideas? By the way obj is a PFObject
The error message is telling you that you have an instance of __NSCFString, and you're calling absoluteString on it. __NSCFString is a kind of NSString, so the situation is simply that you expect (for some reason) that you have an NSURL, but you actually have an NSString - so you don't need to call absoluteString.
It would be good to understand why you think you have an NSURL and whether you will ever have one in this piece of code. The inputs should really be consistent, but if not you can check the class and decide how to get the string version.
It looks like you're trying to convert a NSString to an NSURL with this line:
NSURL *theUrl = [[obj objectForKey:#"image"] url];
But that's not how you convert an NSString to an NSURL and so your NSString isn't being changed to an NSURL as you'd like. Instead, it seems as if it's remained an NSString, thus the error.
There's no need to convert the NSString to an NSURL if the only purpose of that NSURL is to be converted back to an NSString on the next line by accessing its absoluteString property; but if you do in fact need theURL to be an NSURL for reasons beyond the code you've posted (for example, if you need to access the NSURL variable later in your code), try this instead to properly convert your string into an url:
NSURL *theUrl = [NSURL URLWithString:[obj objectForKey:#"image"]];

Creating NSURL with custom query parameter returns nil

I have a UISearchBar from which I'm extracting the text that represents an address and building from it a JSON URL for Google Geocoder.
NSString* address = searchbar.text;
NSString* url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false", address];
If I copy & paste the url from debug window to the browser it works like a charm but when I try to convert it to NSURL i get nil
NSURL* theUrl = [NSURL URLWithString:url];
Any ideas?
I added the encoding to the address prior to concatenating the url and that fixed the problem so now the code looks like this:
NSString* address = searchbar.text;
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, CFBridgingRetain(address), NULL, (CFStringRef)#"!*'();:#&=+$,/?%#[]", kCFStringEncodingUTF8));
NSString* url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false", encodedString];

Data argument not used by format string but it works fine

I used this code from the Stack Overflow question: URLWithString: returns nil:
//localisationName is a arbitrary string here
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* stringURL = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#,Montréal,Communauté-Urbaine-de-Montréal,Québec,Canadae&output=csv&oe=utf8&sensor=false", webName];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
When I copied it into my code, there wasn't any issue but when I modified it to use my url, I got this issue:
Data argument not used by format string.
But it works fine. In my project:
.h:
NSString *localisationName;
.m:
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* stringURL = [NSString stringWithFormat:#"http://en.wikipedia.org/wiki/Hősök_tere", webName];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
[_webView loadRequest:[NSURLRequest requestWithURL:url]];
How can I solve this? Anything missing from my code?
The # in the original string is used as a placeholder where the value of webName is inserted. In your code, you have no such placeholder, so you are telling it to put webName into your string, but you aren't saying where.
If you don't want to insert webName into the string, then half your code is redundant. All you need is:
NSString* stringURL = #"http://en.wikipedia.org/wiki/Hősök_tere";
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
[_webView loadRequest:[NSURLRequest requestWithURL:url]];
The +stringWithFormat: method will return a string created by using a given format string as a template into which the remaining argument values are substituted. And in the first code block, %# will be replaced by value of webName.
In your modified version, the format parameter, which is #"http://en.wikipedia.org/wiki/Hősök_tere", does not contain any format specifiers, so
NSString* stringURL = [NSString stringWithFormat:#"http://en.wikipedia.org/wiki/Hősök_tere", webName];
just runs like this (with the warning Data argument not used by format string.):
NSString* stringURL = #"http://en.wikipedia.org/wiki/Hősök_tere";

Convert an NSURL to an NSString

I have an app where the user can choose an image either from the built-in app images or from the iphone photo library. I use an object Occasion that has an NSString property to save the imagePath.
Now in the case of the built-in app images I do get the file name as an NSString an save in the [occasion imagePath]. But in the 2nd case where the user picks an image form the photo library I get an NSURL which I want to convert to an NSString to be able to save it in [occasion imagePath].
Is it possible to convert the NSURL to an NSString?
In Objective-C:
NSString *myString = myURL.absoluteString;
In Swift:
var myString = myURL.absoluteString
More info in the docs:
If you're interested in the pure string:
[myUrl absoluteString];
If you're interested in the path represented by the URL (and to be used with NSFileManager methods for example):
[myUrl path];
Try this in Swift :
var urlString = myUrl.absoluteString
Objective-C:
NSString *urlString = [myURL absoluteString];
Swift update:
var myUrlStr : String = myUrl.absoluteString
I just fought with this very thing and this update didn't work.
This eventually did in Swift:
let myUrlStr : String = myUrl!.relativePath!
You can use any one way
NSString *string=[NSString stringWithFormat:#"%#",url1];
or
NSString *str=[url1 absoluteString];
NSLog(#"string :: %#",string);
string :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAAA1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif
NSLog(#"str :: %#", str);
str :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAA-A1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif
In Swift :-
var str_url = yourUrl.absoluteString
It will result a url in string.

Resources