我正在尝试从页面获取 XML,但NSURLConnection
没有返回任何内容。
- (void)downloadDataWithMission:(NSString *)mission
{
// Create a new data container for the stuff that comes back from the service
xmlData = [[NSMutableData alloc] init];
// Construct a URL that will ask the service for what you want
NSString *urlstring = [NSString stringWithFormat:@"http://www.google.com/"];
// , mission, [self getCountry]
NSURL *url = [NSURL URLWithString:urlstring];
// Put that URL into an NSURLRequest
NSURLRequest *req = [NSURLRequest requestWithURL:url];
// Create a connection that will exchange this request for data from the URL
urlConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
}
# pragma mark NSURLConnection
- (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
[xmlData setLength:0];
}
// This method will be called several times as the data arrives
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Add the incoming chunk of data to the container we are keeping
// The data always come in the correct order
[xmlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// We are just checking to make sure we are getting the XML
NSString *xmlCheck = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];
NSLog(@"xmlCheck = %@", xmlCheck);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// Release the connection object, we're done with it
urlConnection = nil;
// Release the xmlData object, we're done with it
xmlData = nil;
// Grab the description of the error object passed to us
NSString *errorString = [NSString stringWithFormat:@"Connection Failed: %@", [error localizedDescription]];
// Create and show an alreat view with this error displayed
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
}
@end
为什么连接不起作用?这是代表的问题吗?在另一个项目中,一切正常。这些项目中的基本 SDK 相同 - iOS 6.1。