NSURL Connection will/won't load data - iphone

So here's my issue:
I followed the NSURLConnection tutorial in the iPhone Developer Documentation almost to the T, and it only kinda works.
Here's where it all goes wrong:
The object seems to be created correctly and delegates to connectionDidFinishLoading, but with any URL I try to load the response data always ends up only being 0 bytes. I am running in the simulator if that makes any difference.
Here's my relevant code:
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"WVFS Player";
//create a request
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://wvfs.josh-kaplan.com/nowPlaying.php"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create a connection
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(theConnection) {
// create the datum
responseData=[[NSMutableData data] retain];
} else {
// code this later
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// make it work
NSLog(#"Succeeded! Received %d bytes of data:",[responseData length]);
// release it
[connection release];
[responseData release];
}
And here's my log output:
[Session started at 2010-03-14 09:01:09 -0400.]
2010-03-14 09:01:14.784 WVFS[19571:207] Succeeded! Received 0 bytes of data:
Any ideas?

You forgot to implement connection:didReceiveData:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}

Related

Inconsistent results from NSURL

Using the following code to make my requests, what i've noticed is that data will sometimes not be loaded or fully loaded, this always happens when the app first starts. Any thoughts? I've tried putting in [tableView refresh] in the connectionDidFinishLoading, but that doesn't seem to help, any ideas? Thanks for looking
.h:
NSMutableData *responseData;
.m:
- (void)load {
NSURL *myURL = [NSURL URLWithString:#""];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[responseData release];
[connection release];
[textView setString:#"Unable to fetch data"];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[responseData
length]);
NSString *txt = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding] autorelease];
}
Are you sure your data did not load? Try [tableView reloadData]; instead of refresh.

Using NSURLConnection WebService

i get the follwing error below when i run the program given below
Error:
Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x5948b80 {NSUnderlyingError=0x5948ac0 "bad URL", NSLocalizedDescription=bad URL}
wat i need to do plz suggest me
thank u..
the code is given below
#implementation WebSampleViewController
- (void)viewDidLoad
{
[super viewDidLoad];
dataWebService = [[NSMutableData data] retain];
NSMutableURLRequest *request = [[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#" http://www.googleapis.com/customsearch"]] retain];
NSURLConnection *myConnection = [NSURLConnection connectionWithRequest:request delegate:self];
[myConnection start];
[super viewDidLoad];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[dataWebService setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[dataWebService appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:dataWebService encoding:NSUTF8StringEncoding];
NSLog(#"Response: %#",responseString);
[responseString release];
[dataWebService release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error during connection: %#", [error description]);
}
You should not retain request instance of type NSMutableURLRequest.
You have an leading white space in your String URL.
Use the below code .
NSMutableURLRequest *request = [[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.googleapis.com/customsearch"]];
I think, you should check your URL , I give the same "Not Found" as on iPhone.
Try it without the space at the beginning of your URL string.
You have to remove whitespace in your url

Way to force iOS action to wait until action before complete?

I have an iOS action - (void)download; - which I have running at the launch of my iOS application.
However, I need another - (void)showData;- which displays data on a UIMapView to wait until all the data has been downloaded through - (void)download - before it begins. Just wondering if anyone knows a way to do that?
Thanks.
First send - (void)download; request and put a progress hud to the ui so user will know that you are downloading data, once you are done with download dismiss progress hud and run your - (void)showData; method
- (void)download{
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
//display loading hud here
} else {
// oh noes!
}
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
int kb = [receivedData length] / 1024;
//dismiss hud here
[self showData];
}

Get URL File Size before parsing

Me again! I am using NSURL to get a file then parse it. I have been looking for a couple of hours now on a progressbar i am trying to implement in my app. I know I first need to get the file size, then keep updating how much data i've downloaded as I continue to pull. I have seen the example using "ASIHTTPRequest" but is there a way to do it with what I already have?
Here is where I start the download.
-(void)parseNewData {
//start network activity spinner and release controller when done
parserDone = NO;
[root downloadIcon];
//create pool to avoid memory leak
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// get the XML path and start parsing
NSURL *pathURL = [NSURL URLWithString:#"http://www.mysite.com/myfile.xml"];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:pathURL];
[parser setDelegate:self];
[parser parse];
//drain pool
[pool drain];
[pool release];
}
Can someone point me in the right direction on how to get file size, then how to update how much I've downloaded. Thanks in advance!
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
CGFloat size = [[NSString stringWithFormat:#"%lli",[response expectedContentLength]] floatValue];
NSLog(#"Size : %f",size);
}
Above code will give you total size
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
totalDownloadedData += [data length]; // global integer
NSLog(#"Status : %d/%f",totalDownloadedData,size);
}
Above code will show you current status of downloading
You need to use NSURLConnection if you want to get the file size and the progress. You get delegate methods which you can use to monitor progress. The didSendBodyData: delegate method tells you how much data there is in bytes. The connectionDidFinishLoading is where you uget receivedData to use in your NSXMLParser code.
NSURLRequest *theRequest = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
receivedData = [[NSMutableData data] retain];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
// This method is called when the server has determined that it
// has enough information to create the NSURLResponse.
// It can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
// receivedData is an instance variable declared elsewhere.
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
// release the connection, and the data object
// inform the user
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
[connection release];
// receivedData is declared as a method instance elsewhere
[receivedData release];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite{
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

Load image from url in iPhone, only if small

I'm using initWithContentsOfURL of NSData to load an image from a url. However, I don't know the size of the image beforehand, and I would like to the connection to stop or fail if the response exceeds a certain size.
Is there a way to do this in iPhone 3.0?
Thanks in advance.
You can't do it directly via NSData however NSURLConnection would support such a thing by loading the image asynchronously and using connection:didReceiveData: to check how much data you have received. If you go over your limit just send the cancel message to NSURLConnection to stop the request.
Simple example: (receivedData is defined in the header as NSMutableData)
#implementation TestConnection
- (id)init {
[self loadURL:[NSURL URLWithString:#"http://stackoverflow.com/content/img/so/logo.png"]];
return self;
}
- (BOOL)loadURL:(NSURL *)inURL {
NSURLRequest *request = [NSURLRequest requestWithURL:inURL];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
if (conn) {
receivedData = [[NSMutableData data] retain];
} else {
return FALSE;
}
return TRUE;
}
- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response {
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data {
[receivedData appendData:data];
if ([receivedData length] > 5120) { //5KB
[conn cancel];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
// do something with the data
NSLog(#"Succeeded! Received %d bytes of data", [receivedData length]);
[receivedData release];
}
#end