[iOS9] NSURLSession does not work?

Hi,


I have a problem with this code


@interface NSString(urlPost)
-(NSString*) post:(NSString *)poststr;
@end

@implementation NSString(urlPost)
-(NSString*) post:(NSString *)poststr
{
    NSData *postData = [poststr dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [request setURL:[NSURL URLWithString:self]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    [request setHTTPShouldHandleCookies:YES];

    [[NSURLSession sharedSession] downloadTaskWithRequest:request completionHandler:^(NSURL * __nullable location, NSURLResponse * __nullable response, NSError * __nullable error) {
        NSLog(@"X %@", response); //WILL NEVER BE CALLED....
    }];

    [[NSURLSession sharedSession] dataTaskWithRequest:request
                                    completionHandler:^(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error)
    {
        NSLog(@"[WEB] Response Code: %@", response); //WILL NEVER BE CALLED....
    }];
}


the NSLogs will never be printed.


Other information

    NSString *test = [@"https://mysite.com:1234/CMD_LOGIN" post:@"POSTDATA=TEST"];
    NSLog(@"--> %@", test);


how to fix this?


Tanks!

Replies

NSURLSessionTasks are in `suspended` state when created. You need to resume them to make them work.

See URL Loading System Programming Guide,

Check lines like this in the code sippets included in the guide above:

[downloadTask resume];