Problem with Tiny URL - iphone

I am developing Twitter API to my application. In my app, I want to display the tiny url with parsed xml link in UITexField as dynamically. statically, I could able to display tiny url in UITextField, but dynamically I am not able to display the tiny url. Please help me!
Code: statically(Working fine),
NSURL *url = [NSURL URLWithString"http://tinyurl.com/api-create.php?
url=https://gifts.development.xxxxx.edu/xxxx/Welcome.aspx?appealcode=23430"];
NSString *link = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];
Dynamically,
NSString * tiny = [NSString stringWithFormat:#"http://tinyurl.com/api-create.php? url=%#", shtUrl];//shtUrl is parsed string
NSURL *url = [NSURL URLWithString:tiny];
NSString *link = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];
In above, dynamically app running without warning and error, but url not displayed and when I am checking debugger, url and link both are show nil value. But shtUrl show whole url value as properly.
I tried with all NSURL class and instance methods and String methods also.

In this line of your code:
NSString * tiny = [NSString stringWithFormat:#"http://tinyurl.com/api-create.php? url=%#", shtUrl];
there is a space after the 'api-create.php?'. This will result in a space in the formated string you are creating and will probably result in URLWithString: being unable to parse the url and returning nil.
Remove the extra space (assuming that it is really there and not just a cut-n-paste error) and see if that fixes the problem.
It's also possible that the shtUrl that you are building a tinyurl for contains special characters that would need to be urlencoded (i.e. percent escaped.) Try adding this:
NSString * encodedShtUrl = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)shtUrl,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
kCFStringEncodingUTF8 );
to encode the shtUrl, then use the encodedShtUrl when creating tiny:
NSString * tiny = [NSString stringWithFormat:#"http://tinyurl.com/api-create.php? url=%#", encodedShtUrl];
See http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/ for more about the escaping.

Related

NSURL is null while NSString is correct in Objective-C

I have an NSString containing a url and when I allocate NSURL with the NSString, NSURL outputs (null). It's because there are some illegal characters in the url, which NSURL can't read without encoding the NSString containing the url.
NSString *u = [incomingUrlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:u];
NSLog(#"INCOMINGURLSTRING: %#" , u);
NSLog(#"URL: %#" , url);
Output is:
INCOMINGURLSTRING: /url/path/fileName_blå.pdf
URL: (null)
incomingUrlString contains the Norwegian letter "å", which I think is the reason for the NSURL being (null)
I also tried this:
NSString *trimmedString = [file stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)trimmedString, NULL, (CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ", kCFStringEncodingUTF8);
NSLog(#"TRIMMEDSTRING: %#" , trimmedString);
NSLog(#"ENCODEDSTRING: %#" , [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);
NSURL *url = [NSURL URLWithString:encodedString];
NSLog(#"URL: %#" , url);
Here the output is:
TRIMMEDSTRING: /url/path/fileName_blå.pdf
ENCODEDSTRING: /url/path/fileName_blå.pdf
URL: %2Furl%2FPath%2FfileName_bl%C3%A5.pdf
My goal is to load the URL into a UIWebView. It works for all the other incoming urls except for this one, they all look the same except for the filename. This is the only one containg an illegal character. But I have to find a way to encode this, because there will be more files containg either "æ", "ø" or "å" in the future.
I know the output does not look correct according to url standards, which I did on purpose. I can't show the correct url with http://blah blah because of security reasons.
Can anyone help?
The method you're using for percent-encoding the characters in the string also escapes legal URL characters. This would be appropriate if you were encoding a URL parameter, in this case though it would be better to simply use stringByAddingPercentEscapesUsingEncoding: because it leaves the characters that are part of the URL's structure (':', '/', etc.) intact:
NSString *u = #"http://example/path/fileName_blå.pdf";
u = [u stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:u];
NSLog(#"%#", url); // http://example.com/path/fileName_bl%C3%A5.pdf
If you have an URL that is a file path you must use + (id)fileURLWithPath:(NSString *)path. For the URLWithString: method the String must contain a scheme like file:// or http://.
stringByAddingPercentEscapesUsingEncoding is deprecated.
The new way (iOS 7+) to do it is:
NSString *encoded = [raw stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet];
File path is defined by https://www.rfc-editor.org/rfc/rfc8089.
The key part is to allow characters . and / and disallow %. CharacterSet.urlPathAllowed fits the requirements.
Output with your example:
incomingString: /url/path/fileName_blå.pdf
encodedString: /url/path/fileName_bl%C3%A5.pdf
URL: /url/path/fileName_bl%C3%A5.pdf
I found also that for some North European characters, NSISOLatin1StringEncoding fits better.
- (void) testEncoding {
NSString * urlString = #"http://example/path/fileName_blå.pdf";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding];
NSURL * url = [NSURL URLWithString:urlString];
NSLog(#"URL: %#", url);
}

NSString to NSURL?

Trying to convert a string to NSURL and this is not happening.
barcodeTextLabel.text = foundCode.barcodeString;
urlToGrab = [NSString stringWithFormat:#"%#", foundCode.barcodeString]; // foundCode.barcodeString is an NSString
urlToGrab shows the following "error invalid CFStringRef"
This is how you create an NSURL from an NSString:
NSURL *url = [NSURL URLWithString:#"http://www.google.com"];
You can use following for creating the file path to url.
NSURL *yourURL = [NSURL fileURLWithPath:#"/Users/xyz/Desktop/abc.sqlite"];
If foundCode.barcodeString is the string you want as your URL, then (like the above answer) use the NSURL class method URLWithString:(NSString *).
Your code should look like:
NSURL urlToGrab = [NSURL URLWithString:foundCode.barcodeString];
Where is your error coming into to play? The way your code is, urlToGrab is an instance of NSString. I would imagine you would get an error like you described if you tried to make an HTTP request on an NSString rather than NSURL.
Swapnali patil's answer works, but I will add an explanation.
You will get a nil if the format of NSString doesn't fit file criteria for NSURL (file:///xxx/file.ext).
My needs were with loading a JPG image via URL file path to nsdata; NSURL * u=[[NSURL alloc] initWithString:fpath] returned nil, but NSURL *yourURL = [NSURL fileURLWithPath:fpath] as in mentioned answer worked. A URL for files will be file:///users/xxx/pic.jpg format and give disk access. NSURL * u=[[NSURL alloc] initWithString:(NSString*) ] will also give nil object if nsstring is web URL but if missing http://

NSURL value goes null when url string parameter has space..?

I am parsing xml through my aspx page to my iphone app. I am doing this way to get XML data from url and append into NSData like this below.
NSString *urlString =
[NSString stringWithFormat:#"http://www.abc.com/parsexml.aspx?query=%#",
searchBar.text];
NSURL *url = [NSURL URLWithString:urlString];
error comes when my urlString has whitespace between characters e.g(http://www.abc.com/parsexml.aspx?query=iphone 32gb 3gs)
please help me. What should i do to resolve this issue.
Use NSString's -(NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding; to encode the url request data.
Check the doc here.
NSString *urlString =
[NSString stringWithFormat:#"http://www.abc.com/parsexml.aspx?query=%#",
[searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
You Can Use %20 Instead of Space Remove Space By %20 in your URL String
Hope It Will Help You..

NSURL with string

I have problem with NSURL. I am trying to create NSURL with string
code
NSString *prefix = (#"tel://1234567890 ext. 101");
NSString *dialThis = [NSString stringWithFormat:#"%#", prefix];
NSURL *url = [[NSURL alloc] initWithString:dialThis];
NSLog(#"%#",url);
also tried
NSURL *url = [NSURL URLWithString:dialThis];
but it gives null . what is wrong ?
Thanks..
Your problem is the unescaped spaces in the URL. This, for instance, works:
NSURL *url = [NSURL URLWithString:#"tel://1234567890x101"];
Edit: As does this..
NSURL *url2 = [NSURL URLWithString:[#"tel://1234567890 ext. 101"
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Before passing any string as URL you don't control, you have to encode the whitespace:
NSString *dialThis = [prefix stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// tel://1234567890%20ext.%20101
As a side note, iOS is not going to dial any extension. The user will have to do that manually.
From Apple URL Scheme Reference: Phone Links:
To prevent users from maliciously redirecting phone calls or changing the behavior of a phone or account, the Phone application supports most, but not all, of the special characters in the tel scheme. Specifically, if a URL contains the * or # characters, the Phone application does not attempt to dial the corresponding phone number.
Im not sure the "ext." in phone number can be replce by what value? but you can try like this,
NSString *prefix = [NSString stringWithString: #"tel://1234567890 ext. 101"];
NSString *dialThis = [NSString stringWithFormat:#"%#", prefix];
NSURL *url = [NSURL URLWithString:[dialThis stringByReplacingOccurrencesOfString:#" ext. " withString:#"#"]];
// it might also represent by the pause symbol ','.
you can go to find the ext. is equivalent to what symbol in the phone, then replace it.
but dunno it can be work in actual situation or not....
As with iOS 9.0,
stringByAddingPercentEscapesUsingEncoding:
has been deprecated.
Use the following method for converting String to NSURL.
let URL = "URL GOES HERE"
let urlString = URL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())
If you've got something you think should be a URL string but know nothing about how URL strings are supposed to be constructed, you can use NSURL's URLWithDataRepresentation:relativeToURL: method. It parses the URL string (as bytes in an NSData) and percent-encodes characters as needed. Use the NSUTF8StringEncoding for best results when converting your NSString to NSData.
NSURL *url = [NSURL URLWithDataRepresentation:[#"tel:1234567890 ext. 101" dataUsingEncoding:NSUTF8StringEncoding] relativeToURL:nil];
NSLog(#"%#",url);
creates a URL with the string 1234567890%20ext.%20101
It attempts to do the right thing. However, for best results you should find the specification for the URL scheme you using and follow it's syntax to create your URL string. For the tel scheme, that is https://www.rfc-editor.org/rfc/rfc3966.
P.S. You had "tel://" instead of "tel:" which is incorrect for a tel URL.
Try this one, It works for me....
NSString *prefix = (#"tel://1234567890 ext. 101");
NSString *dialThis = [NSString stringWithFormat:#"%#", prefix];
NSURL *url = [NSURL URLWithString:[queryString stringByReplacingOccurrencesOfString:#" " withString:#"%20"]];
NSLog(#"%#",url);
Make an extension for use in any part of the project as well:
extension String {
var asNSURL: NSURL! {
return NSURL(string: self)
}
}
From now you can use
let myString = "http://www.example.com".asNSURL
or
myString.asNSURL

stringWithContentsOfURL not working with certain string

I have code similar to the following with a URL like this... If I use the first *url, webpage will return null. If I put this URL into a URL shortening system like bit.ly it does work and returns the pages HTML as a string. I can only think I have invalid characters in my first *url? Any ideas?
NSString *url =#"http://www.testurl.com/testing/testapp.aspx/app.detail/params.frames.y.tpl.uk.item.1.cm_scid.TB-test/left.html.|metadrill,html/walk.yah.ukHB?cm_re=LN-_-OnNow-_-TestOne";
//above *url does not work, one below does
NSURL *url =[NSURL URLWithString: #"http://bit.ly/shortened"];
NSString *webpage = [NSString stringWithContentsOfURL:url];
You probably need to escape some characters in the first URL, as follows:
NSString *url =#"http://www.testurl.com/testing/testapp.aspx/app.detail/params.frames.y.tpl.uk.item.1.cm_scid.TB-test/left.html.|metadrill,html/walk.yah.ukHB?cm_re=LN-_-OnNow-_-TestOne";
NSString *escapedURL = [url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString *webpage = [NSString stringWithContentsOfURL:[NSURL URLWithString:escapedURL]];
The construction of the URL and its fetch will fail if the URL contains characters that aren't escaped properly (looking at your URL, it's probably the pipe (|), question mark, or underscore).