美文网首页
NSURLSession的簡單使用

NSURLSession的簡單使用

作者: IPFK | 来源:发表于2017-10-24 22:05 被阅读0次

包括四個會話

  • 簡單會話-通過NSURLSession靜態方法+sharedSession獲得NSURLSession對象
NSString *strURL = [[NSString alloc] initWithFormat:@"http://xxx/WebService.php?email=%@&type=%@&action=%@", @"xxx@xxx.com", @"JSON", @"query"];

    strURL = [strURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//將字符串轉化成URL字符串,例如"<"的URL編碼是"%3C"

    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
        ^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"请求完成...");
        if (!error) {
            NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self reloadView:resDict];
            });
        } else {
            NSLog(@"error : %@", error.localizedDescription);
        }
    }];

    [task resume];

  • 默認會話(default session)-通過NSURLSession靜態方法+sessionWithConfiguration:或者+sessionWithConfiguration:delegate:delegateQueue:獲得NSURLSession對象
    1,以下為GET方法請求數據
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfig delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

2,以下是POST請求,GET請求是NSURLRequest,POST請求是NSMutableURLRequest

    NSString *strURL = @"http://xxx/WebService.php";

    NSURL *url = [NSURL URLWithString:strURL];

    NSString *post = [NSString stringWithFormat:@"email=%@&type=%@&action=%@", @"xxx@xxx.com", @"JSON", @"query"];
    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];

    NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfig delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
        ^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"请求完成...");
        if (!error) {
            NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            [self reloadView:resDict];
        } else {
            NSLog(@"error : %@", error.localizedDescription);
        }
    }];

    [task resume];

3,下載圖片

- (IBAction)onClick:(id)sender {

    NSString *strURL = [[NSString alloc] initWithFormat:@"http://xxx/download.php?email=%@&FileName=test1.jpg", @"xxx@xxx.com"];

    NSURL *url = [NSURL URLWithString:strURL];

    NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url];

    [downloadTask resume];

}

#pragma mark -- 实现NSURLSessionDownloadDelegate委托协议
//下載中的方法,可以用來改變下載進度條
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    
    float progress = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
    [self.progressView setProgress:progress animated:TRUE];
    NSLog(@"进度= %f", progress);
    NSLog(@"接收: %lld 字节 (已下载: %lld 字节)  期待: %lld 字节.", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}

//下載完成後調用的方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {

    NSLog(@"临时文件: %@\n", location);

    NSString *downloadsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, TRUE) objectAtIndex:0];

    NSString *downloadStrPath = [downloadsDir stringByAppendingPathComponent:@"test1.jpg"];
    NSURL *downloadURLPath = [NSURL fileURLWithPath:downloadStrPath];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSError *error = nil;
    if ([fileManager fileExistsAtPath:downloadStrPath]) {
        [fileManager removeItemAtPath:downloadStrPath error:&error];
        if (error) {
            NSLog(@"删除文件失败: %@", error.localizedDescription);
        }
    }

    error = nil;

    if ([fileManager moveItemAtURL:location toURL:downloadURLPath error:&error]) {
        NSLog(@"文件保存: %@", downloadStrPath);
        UIImage *img = [UIImage imageWithContentsOfFile:downloadStrPath];
        self.imageView1.image = img;
        
    } else {
        NSLog(@"保存文件失败: %@", error.localizedDescription);
    }
}
  • 短暫會話(ephemeral session)-通過NSURLSessionConfiguration靜態方法+ephemeralSessionConfiguration獲得
  • 後臺會話(background session)-通過NSURLSessionConfiguration靜態方法+backgroundSessionConfigurationWithIdentifier:獲得

包括三種形式的任務

  • 數據任務(data task) NSURLSessionDataTask類
  • 上傳任務(upload task) NSURLSessionUploadTask類
  • 下載任務(download task) NSURLSessionDownloadTask類

相关文章

  • NSURLSession的簡單使用

    包括四個會話 簡單會話-通過NSURLSession靜態方法+sharedSession獲得NSURLSessio...

  • 簡簡單單。

    想做一個熱愛生活的女子,希望醒來後你可以為我做哪怕一年一次的早餐。然後問著窗台花卉的芬芳,哼著歌為它們澆水。一番打...

  • 簡簡單單

    >櫻花飄落是秒速五釐米,不知道你可曾聽過? 三年的時間足夠一個人做什麼? 三年的時間能夠改變一個人嗎? 三年……究...

  • 簡簡單單的2018

    “肥”宅快樂年 頂著肝爆的風險,熬夜已成日常,隨著“再戰一回合”的想法一次又一次在我腦海中出現,我知道這是屬於我的...

  • 簡單的孩子

    簡單的孩子 從不去奢求的太多 心簡單了這世界 就會簡單了許多 該忙碌時就忙碌 該歇息時就歇息 偶而品位簡單的茶 吃...

  • 2文字简单

    我想長這樣一個腦袋,簡簡單單只有文字…

  • 竹報平安

    簡單!

  • 簡單

    愛 純粹 喜歡 單純 習慣 你都在

  • 簡單

    簡單帶來快樂

  • 簡單

    以一颗干净的心 来面对复杂世事 保持纯净 保持简单 如此即可

网友评论

      本文标题:NSURLSession的簡單使用

      本文链接:https://www.haomeiwen.com/subject/dyixpxtx.html