macosnsurlsessiondatatask

NSURLSessionDataTask does not work on macOS, "A server with the specified hostname could not be found."


Why does dataTaskWithURL work on iOS, but not on macOS?

The error message is:

Client-Error: A server with the specified hostname could not be found.

My routine is as follows:

- (void)loadHTML {
    NSString *urlString = @"https://morph.zone/modules/newbb_plus/viewtopic.php?topic_id=12630&forum=10";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error != nil) {
            NSLog(@"Client-Error:%@",error.localizedDescription);
        }
        else {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode < 200 || httpResponse.statusCode > 299) {
                NSLog(@"Server-Error:%ld",httpResponse.statusCode);
            }
            else {
                NSLog(@"Data downloaded");
            }
        }
    }];
    [downloadTask resume];
}

Solution

  • For macOS targets, you must explicitly enable “Outbound Connections (Client)” on the “Capabilities” tab:

    capabilities

    Until you do that, all outbound connections will fail with NSURLErrorCannotFindHost error.