Very short snippet: get the output of a URL in Objective-C

Perhaps I should write "Very very very, short snippets", however, is an excellent and convenient "trick" that I am going to show. Executing the "two" lines of code shown below, you can get the output of any URL and manipulate it.

1
2
3
4
5
url = [ NSString stringWithFormat : @ "http://www.appleside.it/" ] ; NSString * url = [ NSString stringWithFormat: @ "http://www.appleside.it/"];
result = [ NSString stringWithContentsOfURL : [ NSURL URLWithString : url ] NSString * result = [ NSString stringWithContentsOfURL: [ NSURL URLWithString: url]
encoding: NSASCIIStringEncoding
] ; error: nil];
"Indirizzo: %@ = %@" , url, result ) ; NSLog (@ "Address:% @ =% @", url, result);

For example, we have many services REST API to solve different problems. Just to give a practical example, imagine volre "compress" (trim) the url http://www.undolog.com, as many services like Twitter, FriendFeed or Facebook. Well we could use this simple code:

1
2
3
4
5
6
url = @ "http://www.undolog.com" ; NSString * url = @ "http://www.undolog.com";
apiRest = [ NSString stringWithFormat : @ "http://api.tr.im/v1/trim_simple?url=%@" ,url ] ; NSString * apiRest = [ NSString stringWithFormat: @ "http://api.tr.im/v1/trim_simple?url =% @", url];
result = [ NSString stringWithContentsOfURL : [ NSURL URLWithString : apiRest ] NSString * result = [ NSString stringWithContentsOfURL: [ NSURL URLWithString: apiRest]
encoding: NSASCIIStringEncoding
] ; error: nil];
"URL Originale: %@ - URL Compresso: %@" ,url, result ) ; NSLog (@ "Original URL:% @ - Compressed URL:% @", url, result);

All the merit, of course, is of the method stringWithContentsOfURL : in that it allows you to load in a string the content (output) of a URL.

There are no comments for this post

Leave a comment

TAG XHTML PERMITS: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERTION CODE:
 <pre></pre> // blocco generico <code></code> // blocco generico [cc_actionscript][/cc_actionscript] // Actionscript [cc_actionscript3][/cc_actionscript3] // Actionscript 3 [cc_css][/cc_css] // CSS Style Sheet [cc_html][/cc_html] // HTML [cc_js][/cc_js] // Javascript [cc_objc][/cc_objc] // Objective-C [cc_php][/cc_objc] // PHP [cc_sql][/cc_sql] // SQL 


Stop SOPA