NSURLConnection Asyncronous Request返回null

时间:2013-02-25 02:58:15

标签: objective-c asynchronous nsurlrequest

按照最近制作的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

不确定有什么问题......有什么建议吗?

1 个答案:

答案 0 :(得分:2)

感谢Josh Caswell指出正确的方向,但允许我自己解决这个问题。

将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);
    }
}];