I have implemented an NSURLConnection
that sends a request to a server and receives some data back which is stored in an NSMutableData
object. These are the methods that I implemented as part of NSURLConnectionDelegate
:
-(void)upLoadBook:(NSMutableDictionary *)theOptions{
NSMutableString *theURL = [[NSMutableString alloc] initWithString:@"theURL"];
[theURL appendFormat:@"&Title=%@&Author=%@&Price=%@", [theOptions objectForKey:@"bookTitle"],
[theOptions objectForKey:@"bookAuthor"],
[theOptions objectForKey:@"bookPrice"]];
[theURL appendFormat:@"&Edition=%@&Condition=%@&Owner=%@", [theOptions objectForKey:@"bookEdition"],
[theOptions objectForKey:@"bookCondition"],
_appDel.userID];
NSLog(@"%@\n", theURL);
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:theURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [NSMutableData data];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[receivedData appendData:data];
}
- (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)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data
// receivedData is declared as a method instance elsewhere
//Receives a response after book has been uploaded (Preferably a Book ID...)
responseString = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
NSLog(@"Response String: %@", responseString);
[_options setValue:responseString forKey:@"bookID"];
[self performSegueWithIdentifier:@"UploadSuccessSegue" sender:self];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Whoops." message:@" No internet
connection.\n Please make sure you have a connection to the internet."
delegate:self cancelButtonTitle:@"Ok"
otherButtonTitles: nil];
[alert show];
}
The function uploadBook
seems to be called,however, I never get to didFinishLoading
and didReceiveData
never receives any data. What could be a possible problem. Any hints or clues would be much appreciated.