NSURLConnection未记录到控制台

时间:2013-08-24 10:01:53

标签: ios objective-c ios6 nsurlconnection

我正在尝试从页面获取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。

1 个答案:

答案 0 :(得分:1)

这一行的一切都完美无缺:

NSString *xmlCheck = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];

然而,我认为它不能处理编码。也许谷歌有一个无效的UTF-8字符。请尝试使用NSASCIIStringEncoding,它会起作用。如果你想使用UTF-8,你可能需要深入研究为什么谷歌不符合UTF-8。