NSURLSession、NSURLConnection

NSURLSesstion GET方法  block回調方法
NSString * urlStr = @"http://192.168.1.247:8100/stream?cname=cha_26&seq=0&token=xxx"; NSURLSession * session = [NSURLSession sharedSession]; NSURLSessionTask * sessionTask = [session dataTaskWithURL:urlStr completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@""); }]; [sessionTask resume];

NSURLSesstion POST方法 block回調方法緩存

NSURL * url = [NSURL URLWithString:@"http://www.daka.com/login"];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [@"username=daka&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSession * session = [NSURLSession sharedSession];
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"");
    }];
    [task resume];

 NSURLSesstion 代理方法服務器

NSURLSessionDataDelegate代理方法

 NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    NSURLSessionDataTask * task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.daka.com/login?userName=daka&pwd=123"]]];
    [task resume];
// 1.接收到服務器的響應
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    // 容許處理服務器的響應,纔會繼續接收服務器返回的數據
    completionHandler(NSURLSessionResponseAllow);
}

// 2.接收到服務器的數據(可能調用屢次)
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    // 處理每次接收的數據
}

// 3.請求成功或者失敗(若是失敗,error有值)
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    // 請求完成,成功或者失敗的處理
}

 

AFHttpSessionManager GET 請求網絡

AFHTTPSessionManager * session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 5.0f;
    [session GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"downloadProgress");
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"失敗");
        NSLog(@"error:%@",error);
        switch (error.code) {
            case AFNetworkErrorType_NoNetwork :
                NSLog(@"網絡連接失敗,請檢查網絡。");
                break;
            case AFNetworkErrorType_TimedOut :
                NSLog(@"訪問服務器超時,請檢查網絡。");
                break;
            case AFNetworkErrorType_3840Failed :
                NSLog(@"服務器報錯了,請稍後再訪問。");
                break;
            default:
                break;
        }
    }];

AFHttpSessionManager POST 請求session

    [session POST:urlStr parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"downloadProgress");
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失敗");
        NSLog(@"error:%@",error);
    }];

 

    NSURL * url = [NSURL URLWithString:@"http://192.168.101.101:8080/DSPManager/bidding/ssp/process"];
    
    NSURLSession * session = [NSURLSession sharedSession];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [@"bid=aaa&platform=1&appType=1&slotId=222&width=273&height=230&creativeType=0&minCpm=2000" dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (!error) {
            NSLog(@"response--->%@",response);
            NSLog(@"data--->%@",data);
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"dic--->%@",dict);
        }else{
            NSLog(@"error--->%@",error);
        }
    }];
    [task resume];

 

    NSURL * url = [NSURL URLWithString:@"http://192.168.101.101:8080/DSPManager/bidding/ssp/process"];
    
    NSURLSession * session = [NSURLSession sharedSession];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
//    request.HTTPBody = [@"bid=aaa&platform=1&appType=1&slotId=222&width=273&height=230&creativeType=0&minCpm=2000" dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * dict1 = @{
                            @"bid"         : @"fengmin",
                            @"platform"    : @1,
                            @"appType"     : @1,
                            @"slotId"      : @"222",
                            @"width"       : @273,
                            @"height"      : @230,
                            @"creativeType": @0,
                            @"minCpm"      : @2000
                           };
    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:dict1 options:0 error:NULL];
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (!error) {
            NSLog(@"response--->%@",response);
            NSLog(@"data--->%@",data);
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"dic--->%@",dict);
        }else{
            NSLog(@"error--->%@",error);
        }
    }];
    [task resume];

 

NSURLSessionDownloadTask

NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@"http://www.daka.com/resources/image/icon.png"] ;
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    // location是沙盒中tmp文件夾下的一個臨時url,文件下載後會存到這個位置,因爲tmp中的文件隨時可能被刪除,因此咱們須要本身須要把下載的文件挪到須要的地方
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
    // 剪切文件
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:path] error:nil];
}];
    // 啓動任務
    [task resume];

NSURLSessionDownloadDelegate代理方法

// 每次寫入調用(會調用屢次)
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
// 可在這裏經過已寫入的長度和總長度算出下載進度
CGFloat progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite; NSLog(@"%f",progress);
}

// 下載完成調用
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didFinishDownloadingToURL:(NSURL *)location {
    // location仍是一個臨時路徑,須要本身挪到須要的路徑(caches下面)
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:nil];
}

// 任務完成調用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {

}

NSURLSessionUploadTask

NSURLSessionUploadTask *task =
[[NSURLSession sharedSession] uploadTaskWithRequest:request
                                           fromFile:fileName
                                  completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
 [self.session uploadTaskWithRequest:request
                            fromData:body
                   completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
 NSLog(@"-------%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
 }];

斷點下載

NSURLSessionDownloadTask提供了與斷點下載相關的幾個方法:app

// 使用這種方式取消下載能夠獲得未來用來恢復的數據,保存起來
[self.task cancelByProducingResumeData:^(NSData *resumeData) {
    self.resumeData = resumeData;
}];

// 因爲下載失敗致使的下載中斷會進入此協議方法,也能夠獲得用來恢復的數據
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    // 保存恢復數據
    self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
}

// 恢復下載時接過保存的恢復數據
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
// 啓動任務
[self.task resume];
- (void)suspend;//讓當前的任務暫停
- (void)resume;//能夠啓動任務,還能夠喚醒suspend狀態的任務
- (void)cancel;//取消當前的任務,你也能夠向處於suspend狀態的任務發送cancel消息,任務若是被取消便不能再恢復到以前的狀態.

NSURLSessionConfiguration

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
// 超時時間
config.timeoutIntervalForRequest = 10;
// 是否容許使用蜂窩網絡(後臺傳輸不適用)
config.allowsCellularAccess = YES;
// 還有不少能夠設置的屬性

有沒有發現咱們使用的Configuration都是默認配置:[NSURLSessionConfiguration defaultSessionConfiguration],其實它的配置有三種類型:ide

+ (NSURLSessionConfiguration *)defaultSessionConfiguration;
+ (NSURLSessionConfiguration *)ephemeralSessionConfiguration;
+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier

表示了NSURLSession幾種不一樣的工做模式.
默認的配置會將緩存存儲在磁盤上,第二種瞬時會話模式不會建立持久性存儲的緩存,第三種後臺會話模式容許程序在後臺進行上傳下載工做.url

除了支持任務的暫停和斷點續傳,我以爲NSURLSession之於NSURLConnection的最偉大的進步就是支持後臺上傳下載任務,這又是一個能夠深刻討論的話題.但在這方面我尚未進行深刻的研究,待後續瞭解以後另行開貼.spa

 

NSURLConnection 代理方法代理

    NSString * urlStrEcode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlStr]];
    NSURL * url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    [request setTimeoutInterval:10];
    
    NSURLConnection * conn = [NSURLConnection connectionWithRequest:request delegate:self];
    [conn start];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"response:%@",response);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"data:%@",data);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
     NSLog(@"connection:%@",connection);
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error:%@",error);
}

NSURLConnection block回調方法code

NSString * urlStr = @"http://192.168.1.247:8100/stream?cname=cha_26&seq=0&token=xxx";
    NSString * urlStrEcode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlStr]];
    NSURL * url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    [request setTimeoutInterval:10];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
    }];
相關文章
相關標籤/搜索