TwitterCounter for @bigclick_dean

dBlog.com.au

My Development Blog

Posts Tagged ‘ NSString ’

I thought i would make this a separate post to the Build your very own Web Browser! tutorial as it can be used for many different purposes and it took me a bit to figure it out.

For my example I am going to be trying to use a file in my local bundle in a UIWebView, my file is going to be called “sample.jpg” and it will be in the root folder of my project, this will work for any folder though.

I will show you the code and then I will explain it.

NSString *imagePath = [[NSBundle mainBundle] resourcePath];
imagePath = [imagePath stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
imagePath = [imagePath stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

NSString *HTMLData = @"
<h1>Hello this is a test</h1>
<img src="sample.jpg" alt="" width="100" height="100" />";
[webView loadHTMLString:HTMLData baseURL:[NSURL URLWithString: [NSString stringWithFormat:@"file:/%@//",imagePath]]];

Line 1
This will get the path to the main bundle root folder.

Line 2
We need the slashes to be double slashed to work correctly in the UIWebView, so we are searching for all instances of “/” and replacing it with “//”

Line 3
Same deal as above but we are searching for a space and replacing it with the HTML equivalent of %20

Line 4
This is putting some sample data together for out UIWebView, you will see that we have set the images source to just our “sample.jpg” file as it is sitting in the root folder, if it was in a folder called “images” we would need to set the source to “images//sample.jpg”. Remember the double slashing!

Line 5
This is pretty much the same as my example in the tutorial although we are setting the baseURL to the root of our application bundle, this allows us to reference everything relatively instead of absolute paths.

Well thats about it, if you have done my Build your very own Web Browser! tutorial you will be able to replace the contents of applicationDidFinishLaunching with the above code (don’t forget to leave the makeKeyAndVisible line in there) and you will be loading content from your local device in no time!

Popularity: 10% [?]