ios - NSURLSession tasks creation -


i'm working on networkcommunicator helper class, handle connection server,i'm using nsurlsession api , have question creation of nsurlsession tasks. there 2 ways create taks:

1 - nsurlrequest

2 - url

i wondering preferred way? more specific in way life easier (adding headers, setting verb types, etc'..).

thanks

you more flexible when use methods take nsurlrequest example datataskwithrequest: method. way can customize http method, request body, headers, every parameter of nsurlrequest because creates it.

methods take nsurl create nsurlrequest for you under hood cannot modify request afterwards. example datataskwithurl: method creates http get request specified url , cannot change post.

example of creating task nsurlrequest. can see can flexible here:

// create simple json data. nsdata *jsondata = [nsjsonserialization datawithjsonobject:@{ @"numbers" : @[@1, @2, @3] } options:0 error:nil];  // create post request our json request body. nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url];  // set http method. request.httpmethod = @"post";  // set request body. request.httpbody = jsondata;  // create task. nsurlsessiondatatask *task = [[nsurlsession sharedsession] datataskwithrequest:request                                                              completionhandler:^(nsdata *data,                                                                                  nsurlresponse *response,                                                                                  nserror *error) {     ... }]; 

example of creating task using nsurl. here cannot modify request. created you.

// create task. nsurlsessiondatatask *task = [[nsurlsession sharedsession] datataskwithurl:url                                                          completionhandler:^(nsdata *data,                                                                              nsurlresponse *response,                                                                              nserror *error) {  ... }]; 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -