ios – Get data from a request to the main thread

The dataTaskWithRequest methodology runs asynchronously, i.e., later. You possibly can’t simply reference the variables exterior of the block.

The everyday resolution is to offer a block parameter to your methodology that performs this request, a completion handler, and name the completion handler contained in the asynchronous block of dataTaskWithRequest.

E.g., you might need:

- (void)performRequestWithURL:(NSURL *)url completion:(void (^ _Nonnull)(NSString *username, NSString *area, NSError *error))completion {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    NSURLSession *session = [NSURLSession sharedSession];

    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(nil, nil, error);

        NSString *requestReply = [[NSString alloc] initWithData:knowledge encoding:NSUTF8StringEncoding];

        NSRange rangeUsername = [requestReply rangeOfString:@"<username>"];
        NSString *username = [requestReply substringFromIndex:rangeUsername.location];
        username = [username stringByReplacingOccurrencesOfString:@"<username>" withString:@""];
        username = [username stringByReplacingOccurrencesOfString:@"</username>" withString:@""];

        NSRange rangeDomain = [requestReply rangeOfString:@"<SIP_domain>"];
        NSString *area = [requestReply substringFromIndex:rangeDomain.location];
        area = [domain stringByReplacingOccurrencesOfString:@"<SIP_domain>" withString:@""];
        area = [domain stringByReplacingOccurrencesOfString:@"</SIP_domain>" withString:@""];

        dispatch_async(dispatch_get_main_queue(), ^{
            completion(username, area, nil);
    }] resume];

And name it like so:

[self performRequestWithURL:url completion:^(NSString *username, NSString *domain, NSError *error) {
    if (error) {
        NSLog(@"error = %@", error);

    // use `username` and `domain` here ...

// ... however not right here, as a result of the above runs asynchronously

Leave a Reply

Your email address will not be published.