Асинхронный запрос NSURLConnection возвращает значение null

Следуя недавно созданному учебнику YouTube, попробуйте асинхронно подключиться к веб-адресу. Повторная настройка null для ответа, но длина данных больше 0. Я видел другой код, который выполняет проверку как null, так и длины, который я не выбрасывал, просто NSLog их.

@implementation ViewController

-(void)fetchAddress:(NSString *)address  {

NSLog(@"Loading Address: %@", address);
[iOSRequest requestToPath:address onCompletion:^(NSString *result, NSError *error)  {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (error)  {
            [self stopFetching:@"Failed to Fetch"];
            NSLog(@"%@", error);
        } else  {
            [self stopFetching:result];
            NSLog(@"Good fetch:  %@", result);
        }
        });
    }];

}


- (IBAction)fetch:(id)sender {

    [self startFetching];
    [self fetchAddress:self.addressField.text];
    NSLog(@"Address: %@", self.addressField.text);

}


-(void)startFetching  {

    NSLog(@"Fetching...");
    [self.addressField resignFirstResponder];
    [self.loading startAnimating];
    self.fetchButton.enabled = NO;

}


-(void)stopFetching:(NSString *)result  {

    NSLog(@"Done Fetching  %@", result);
    self.outputLabel.text = result;
    [self.loading stopAnimating];
    self.fetchButton.enabled = YES;

}




@implementation iOSRequest


    +(void)requestToPath:(NSString *)
        path onCompletion:(RequestCompletionHandler)complete  {


    NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init];


    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:path]
        cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
        timeoutInterval:10];


    NSLog(@"path:  %@  %@", path, request);

    [NSURLConnection sendAsynchronousRequest:request
        queue:backgroundQueue
        completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)  {
        NSString *result = [[NSString alloc] initWithData:
            data encoding:NSUTF8StringEncoding];
        if (complete)  {
           complete(result, error);
           NSLog(@"result:  %@ %lu %@", result, (unsigned long)[data length], error);
        }
    }];
}

запрос http://www.google.com> ответ нулевой длина данных 13644

Не уверен, что не так... есть предложения?


person BlizzofOZ    schedule 25.02.2013    source источник
comment
По каким причинам вызов initWithData:encoding: мог завершиться ошибкой?   -  person jscs    schedule 25.02.2013
comment
@JoshCaswell: NSASCIIStringEncoding? Кажется, теперь работает, спасибо!   -  person BlizzofOZ    schedule 25.02.2013


Ответы (1)


Спасибо Джошу Касвеллу за то, что он указал правильное направление, но позволил мне разобраться в этом самому.

Кодировка initWithData изменена с NSUTF8StringEncoding на NSASCIIStringEncoding.

[NSURLConnection sendAsynchronousRequest:request
    queue:backgroundQueue
    completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)  {
    NSString *result = [[NSString alloc] initWithData:
        data encoding:NSASCIIStringEncoding];
    if (complete)  {
       complete(result, error);
       NSLog(@"result:  %@ %lu %@", result, (unsigned long)[data length], error);
    }
}];
person BlizzofOZ    schedule 25.02.2013