我已经实现了一个NSURLConnection
向服务器发送请求并接收一些存储在NSMutableData
对象中的数据。这些是我作为其中一部分实现的方法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];
}
该函数uploadBook
似乎被调用,但是,我从来没有得到didFinishLoading
也didReceiveData
从来没有收到任何数据。可能是什么问题。任何提示或线索将不胜感激。