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?
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.