NSURLConnection Asyncronous Request returns null

2019-09-07 17:07发布

Followed a recently made YouTube tutorial try connecting to web address asynchronously. Retuning null for the response, but the data length is greater than 0. I've seen other code that does both null & length checking, which I didn't throw, just NSLog'd them.

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

request is http://www.google.com> response is null data length is 13644

Not sure what is wrong... any suggestions?

1条回答
Viruses.
2楼-- · 2019-09-07 17:43

Thanks to Josh Caswell for pointing in the right direction, but allowing me to figure it out myself.

Changed the initWithData encoding from NSUTF8StringEncoding to 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);
    }
}];
查看更多
登录 后发表回答