Loading NSData into WebView - objective-c

I have an NSData object and I want to display it in a WebView. Can WebView handle/display NSData objects?
NSData *data = ... // some data I've gotten from NSURLConnection
WebView *webView = ... [[WebView alloc] init];

Yes!
NSData is handled by UIWebView when properly supplied with MIME type.
This snippet loads a .docx file in a WebView
NSString *path = [urlFileInView path];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
webViewForDocsView.delegate = self;
[webViewForDocsView loadData:data MIMEType:#"application/vnd.openxmlformats-officedocument.wordprocessingml.document" textEncodingName:#"UTF-8" baseURL:nil];

Without the Content-Type header, the web view has no way to know how to interpret the data. That's why the Content-Type header was added.
If for some reason you want an NSData capture of network traffic that you can replay whenever you want, consider writing a custom NSURLProtocol. If you write a handler for http then it will override the built-in one; give it a fall-through memory and it can redirect those requests to the real one.

Do it like this
NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
[self.webView loadHTMLString: newStr baseURL:nil];

Related

how to load pdf in binary format on UIWebview iOS?

I want to open a pdf file when user clicks on download button, but the data loaded is decode, how can i convert response data to be as a pdf file? i am not loading it from local document or bundle.
NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL:url];
[webViewForDocsView loadRequest:requestObj];
[self.view addSubview:webViewForDocsView];
To load raw data first create a NSData object with the content of the url response, then load the data by specifying the mime type and data, like the code snippet:
NSURL *url = [[NSURL alloc] initWithString:#"binary file link"];
NSError *error;
/**
* GET the data from a url link
*/
NSData *data = [NSData dataWithContentsOfURL:url
options:NSDataReadingUncached
error:&error];
if (error) { // validation
NSLog(#"data error: %#", error);
}
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.frame];
[self.view addSubview:webView];
/**
* Load the request fro mthe binaray data
*/
[webView loadData:data
MIMEType:#"application/pdf"
textEncodingName:#"utf-8"
baseURL:[NSURL URLWithString:#"http://example.com/"]];

How can i parse local xml file instead of Web xml in Xcode?

Hii it's easy for me to parse a XML file from a web URL using NSXML Parser but i found little bit difficulty in parsing the local XML file.?
consider this,
my parser.m has a method for
-(void)parseRssFeed:(NSString *)url withDelegate:(id)aDelegate {
[self setDelegate:aDelegate];
responseData = [[NSMutableData data] retain];
NSURL *baseURL = [[NSURL URLWithString:url] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:baseURL];
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];}
and i used this method for calling a RSS Feed in one of my viewcontroller.m as
- (void)loadData {
if (items == nil) {
[activityIndicator startAnimating];
Parser *rssParser = [[Parser alloc] init];
[rssParser parseRssFeed:#"http://--some RssFeed url---" withDelegate:self];
[rssParser release];
} else {
[self.tableView reloadData];
}
}
and now instead of the some web Rss Feed Url i have to load my local XML file.
Please help me in this coding where i have to change and include NSBundlePath Resource for my local XML FIle.
Thanks in advance!!!
For a local file you don't need the NSURLConnection to get the data. The following will get a local XML file named "local.xml" into an NSData object:
NSString *path = [[NSBundle mainBundle] pathForResource:#"local" ofType:#"xml"];
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
At this point you should be able to call the same parsing code you use once you have the data from the remote xml file.

Creating a POST/GET request using Objective -C [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Tutorials for using HTTP POST and GET on the iPhone in Objective-C
Is there away to create an NSArray with the correct information like id = 1, name = #"John", score = 100 then send it and receive a response from the server?
Maybe display it inside an NSLog();
Can anyone help answer this question by linking me to a good tutorial, I don't want to use ASIHTTPRequest either. I know it would be much simpler but if there is away to do something without using a load of prewritten code id rather learn how to make something using the functionality the the foundation framework offers before going off using someone elses classes.
What you're looking for is NSMutableURLRequest and the addValue:forHTTPHeaderField method.
Create the request with the URL you wish to communicate with. Load the values you wish to transmit into the header or into the HTTPBody, set your HTTPMethod and then use a NSURLConnection method to send and receive the response.
As for an array with the information you could simply enumerate through the array and add the values to the HTTPHeaderFields. It really depends on what the server is setup to receive.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/10000165i
Has more information.
NSString *urlString = #"http://yoururl.com";
NSURL *url = [NSUL URLWithString:urlString];
NSMutalbeURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSDictionary *headerInformation = [NSDictionary dictionaryWithObjectsAndKeys:#"1",#"id",#"John",#"name",#"100",#"score", nil];
for (NSString *key in [headerInformation allKeys])
{
[request addValue:[dict valueForKey:key] forHTTPHeaderField:key];
}
NSHTTPURLResponse *response = nil;
NSError *error = nil;
// this will perform a synchronous GET operation passing the values you specified in the header (typically you want asynchrounous, but for simplicity of answering the question it works)
NSData *responseData = [NSURLConnection sendSynchronousRequest:request reuturningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response: %#", responseString);
[responseString release];
It might be easier to just use NSData to send a url request and store the response then to reinvent the wheel. Here is some code similar to something in my production project:
+ (NSData *)getProfiles {
NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:#"token"];
// Create string of the URL
NSString *serviceURL = [NSString stringWithFormat:#"http://www.myurlhere.com/getProfiles.php?token=%#", token];
NSLog(#"Service URL : %#", serviceURL);
// Create a NSURL out of the string created earlier. Use NSASCIIStringEncoding to make it properly URL encoded (replaces " " with "+", etc)
NSURL *URL = [NSURL URLWithString:[serviceURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
// Request the url and store the response into NSData
NSData *data = [NSData dataWithContentsOfURL:URL];
if (!data) {
return nil;
}
// Since I know the response will be 100% strings, convert the NSData to NSString
NSString *response = [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
// Test response and return a string that an XML Parser can parse
if (![response isEqualToString:#"UNAUTHORIZED"]) {
response = [response stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
data = [response dataUsingEncoding:NSASCIIStringEncoding];
return data;
} else {
return nil;
}
}
NSLog output:
[Line: 476] +[WebSupport getProfiles]: Service URL : http://www.myurlhere.com/getProfiles.php?token=abcdef0123456789abcdef0123456789

How to get content from URL asynchronously?

I'm trying here to create NSXMLParser from content of URL, it work perfectly well but is there way I can make URL content to be received asynchronously and later create NSXMLParser?
NSURL *url = [[NSURL alloc] initWithString: #"http://www.Xmlfile.com"];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[url release];
Use NSURLConnection to fetch the data asynchronously into an NSData, then use initWithData instead of initWithContentsOfURL.

Objective-C how to get an image from a url

Am having some difficulty getting an Image from a url, and then displaying it in an image well in the interface.
This is the code I'm currently using, it doesn't work and compiles with no errors:
NSURL *url = [NSURL URLWithString:#"http://www.nataliedee.com/061105/hey-whale.jpg"];
NSString *newIMAGE = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
[imageView setImage:[NSImage imageNamed:newIMAGE]];
Any ideas as to what is wrong here?
You are passing in image data as a string to a method that is trying to use that string as the name of the image, which of course doesn't exist.
What you need to do is create an NSData object from your URL dataWithContentsOfURL:, once you have the NSData object use this to create the UIImage via imageWithData:.