iosobjective-cnsurlsessionuploadtask

NSURLSessionUploadTask example in objective-c?


Hi I'm using NSURLSessionDataTask in app to for background http call as follows,

 NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

But, I've 2 server say https://demo.demosite.com and http://214.43.45.35/ when I tried dataTaskWithRequest:request it doesn't support both server.I read here that dataTaskWithRequest:request doesn't support in background?.

NSURLSessionUploadTask support in background when app is not running. Can anyone share NSURLSessionUploadTask callback example?


Solution

  • Below is the example:

     NSData* data = [Your_json_string dataUsingEncoding:NSUTF8StringEncoding];
    
        NSURLSession *session = [NSURLSession sharedSession];
    
        NSURL *url = [NSURL URLWithString:@"your_url"];
    
        NSMutableURLRequest *request =
    
        [[NSMutableURLRequest alloc] initWithURL:url];
    
        [request setHTTPMethod:@"POST"];
    
        NSURLSessionUploadTask *uploadTask = [session         uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            //Perform operations on your response here
        }];
    
        //Don't forget this line ever
        [uploadTask resume];