-1

I am trying to use the below post code with dataTaskWithURL:completionHandler to ensure that my app is not jamming:

NSString *rawStr = [NSString stringWithFormat:@"comments=%@&commentsDate=%@&commentsTime=%@&title=%@&userName=%@&qasidaNumber=%@&theUserId=%@%@%@", textComments.text, lbDate.text, lbTime.text, self.lbTitle.text, self.lbUserName.text , self.lbQasidaId.text, toSaveLink, toSaveUser, myJpg];


NSData *data = [rawStr dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:@"http://MyWebSite.com/InsertNotes.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];
[request setHTTPBody:data];

NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(@"responseData: %@", responseData);

My question is how to use the code with dataTaskWithURL:completionHandler

Ahmed.S.Alkaabi
  • 243
  • 2
  • 10
  • BTW, you are not percent escaping your values that you're adding to `rawData`. If any of those fields included any reserved characters (e.g. `+` and `&`, notably), the data would not be received properly. See http://stackoverflow.com/a/20777164/1271826. – Rob Mar 22 '15 at 11:44

1 Answers1

0

Since you're building a NSURLRequest, you probably want dataTaskWithRequest instead of dataTaskWithURL. That having been said, you might use it like so:

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // use `data` and `error` here

    dispatch_async(dispatch_get_main_queue(), ^{
        // update your UI here
    });
}];
[task resume];

// do not use `data` here, though

Remember, the completionHandler may run on a background thread, so if you want to update the UI or model objects from within the block, you have to manually dispatch that back to the main queue, as shown above.

For more information, please refer to WWDC 2013 video What's New in Foundation Networking, which introduces us to NSURLSession.

Rob
  • 415,655
  • 72
  • 787
  • 1,044