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*。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 有时我在想: 撒但有痛感吗 地狱之火能灼痛他吗 人的灵魂 硫磺之火 地狱门口转着的刀剑 会灼烧伤害那飘荡的灵魂吗 ...
    子兴阅读 5,242评论 7 9