NSURLSession

地址

The behavior of the tasks in a session depends on three things:

  1. the type of session (determined by the type of configuration object used to create it)
  • default session: use a persistent disk-based cache and store credentials in the user’s keychain.
  • Ephemeral sessions: do not store any data to disk; all caches, credential stores, and so on are kept in RAM and tied to the session.
  • Background sessions are similar to default sessions, but has some limit.
  1. the type of task
  • data tasks : send and receive data using NSData objects. Data tasks are intended for short, often interactive requests from your app to a server.
  • download tasks : retrieve data in the form of a file
  • upload tasks : send data in the form of a file
  1. whether the app was in the foreground when the task was created.

Fetching Resources Using System-Provided Delegates

The most straightforward way to use the NSURLSession is to request a resource using system-provided delegates. Using this approach, you need to provide only two pieces of code in your app:

  • Code to create a configuration object and a session based on that object
  • A completion handler routine to do something with the data after it has been fully received
NSURLSession *sessionWithoutADelegate = [NSURLSession sessionWithConfiguration:defaultConfiguration];

NSURL *url = [NSURL URLWithString:@"https://www.example.com/"];

[[sessionWithoutADelegate dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

NSLog(@"Got response %@ with error %@.\n", response, error);

NSLog(@"DATA:\n%@\nEND DATA\n", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

}] resume];

how to understand completion?

+ (void)requestWithUrl:(NSString *)url completion:(void (^)(id, NSString *))completion
{
    NSURLSession* session = [NSURLSession sharedSession];
    NSURL *requestURL = [NSURL URLWithString:url];
    
    [[session
     dataTaskWithURL:requestURL
     completionHandler:^(NSData* data, NSURLResponse* response, NSError* error){
         [[GCDUtil globalQueueWithLevel:DEFAULT] async:^{
             NSHTTPURLResponse* responseFromServer = (NSHTTPURLResponse *)response;
             if (data != nil && error == nil && responseFromServer.statusCode == 200)
             {
                 NSError* parseError = nil;
                 id result = [NSJSONSerialization JSONObjectWithData:data
                                                             options:0
                                                               error:&parseError];
                 
             }
         }];
     }] resume];
}

此处的completion是指你在调用该函数时的设置的一个代码块,这个代码块的参数是一个id对象以及一个NSString*。

你可能感兴趣的:(NSURLSession)