獲取網絡數據請求

寫了幾種獲取網絡數據的方式和下載任務的方式
1.普通的request請求,block回調數據

    {
    /*******************普通request的請求,利用block接收*******************/
    //1.獲取資源
    NSURL *url = [NSURL URLWithString:@"http://news-at.zhihu.com/api/3/news/latest"];
    //2.獲取請求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //3.創建會話
    NSURLSession *session = [NSURLSession sharedSession];
    //4.添加任務
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //錯誤檢查
        if (error != 0) {
            NSLog(@"請求失敗%@",error);
        }else {
            //狀態碼,響應頭內容
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            NSInteger status = httpResponse.statusCode;
            NSDictionary *headerDic = httpResponse.allHeaderFields;
            NSLog(@"status = %ld , headerFields = %@",status,headerDic);
            //獲取json數據
            id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"json = %@",jsonData);
        }
    }];
    //5.發起任務 resume - 恢復
    [dataTask resume];
    }

2.自定義請求,block回調數據

    /*******************自定義request的請求,利用block接收*******************/
    NSURL *url = [NSURL URLWithString:@"http://piao.163.com/m/cinema/list.html?apiVer=6&city=110000"];
    //創建可變Request對象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //緩存策略
    request.cachePolicy = NSURLRequestUseProtocolCachePolicy;
    //超時設置
    request.timeoutInterval = 120;
    //請求方式(默認是get)
    request.HTTPMethod = @"POST";//這里的必須大寫
    //設置請求頭   Accept-Language
    [request setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"];
    
    //session(默認是異步)
    NSURLSession *session = [NSURLSession sharedSession];
    
    //添加任務(block)
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        //錯誤檢查
        if (error != nil) {
            NSLog(@"請求失敗%@",error);
        }else {
            //狀態碼,響應頭內容
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            NSInteger status = httpResponse.statusCode;
            NSDictionary *headerDic = httpResponse.allHeaderFields;
            NSLog(@"status = %ld , headerFields = %@",status,headerDic);
            //獲取json數據
            id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"json = %@",jsonData);
        }
    }];
    
    [dataTask resume];
    

3.自定義session的方式,代理方式
代理方法:

NSURLSessionDataDelegate

內容:

   /*******************自定義session,利用代理接收*******************/
    
    NSURL *url = [NSURL URLWithString:@"http://news-at.zhihu.com/api/3/news/latest"];
    //設置請求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //請求方式是get
    [request setHTTPMethod:@"GET"];
    
    
    //自定義session
    //設置session的配置
    //+defaultSessionConfiguration  用于創建默認類型的Session對象
    //+ephemeralSessionConfiguration 用于創建臨時類型的Session對象
    //+backgroundSessionConfiguration:(NSString *)identifier  用于創建后臺Session對象
    //identifier:作用標示后臺的session,做好和app的bundle id相同
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    //緩存策略
    config.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
    //蜂窩數據
    config.allowsCellularAccess = YES;
    /*
     sessionWithConfiguration:session配置
     delegate:代理 NSURLSessionDataDelegate
     delegateQueue:代理隊列 (主隊列)
     */
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    //直接獲取請求,因為是代理方式
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
    //resume
    [dataTask resume];

代理方法:

#pragma makr- 代理方法
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler{
    //響應頭
    NSLog(@"response : %@",response);
    //必須寫這句話繼續接收響應體
    //(block的回調)
    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
 
    id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"heehhee");
    NSLog(@"json - %@",jsonData );
    
}

4.下載一張圖片

- (IBAction)nomalDownLoad:(UIButton *)sender {
    //獲取一個路徑 ,一張圖片
    NSURL *url = [NSURL URLWithString:@"http://www.pptbz.com/pptpic/UploadFiles_6909/201204/2012041411433867.jpg"];
    NSURLSession *session = [NSURLSession sharedSession];
    //不設置request請求頭,使用默認的
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //打印一下下載到的路徑
        //因為這個路徑是一個臨時文件所以需要把下載的東西移動到另外一個地方
        NSLog(@"位置:%@",location);
        //移動文件
        NSFileManager *manager = [NSFileManager defaultManager];
        NSString *newPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/download.jpg"];
        NSURL *newURL = [NSURL fileURLWithPath:newPath];
        [manager moveItemAtURL:location toURL:newURL error:nil];
        NSLog(@"newURL : %@",newURL);
        //圖片就保存在了本地了
        
    }];
    [task resume];
    
}

5.下載一部電影,用進度條查看進度
頭文件

    __weak IBOutlet UIProgressView *progressView;
    NSURLSessionDownloadTask *downTask;
    //下載好的數據存起來
    NSData *saveData;
    
    NSURLSession *startSession;

這里使用的代理是

NSURLSessionDownloadDelegate

//能暫停的任務
- (IBAction)startDownLoad:(UIButton *)sender {
    
    NSURL *url = [NSURL URLWithString:@"http://vf1.mtime.cn/Video/2012/04/23/mp4/120423212602431929.mp4"];
    //填寫一個配置
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    //用代理來寫,全局變量
    startSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    //建立一個下載任務,全局變量
    downTask = [startSession downloadTaskWithURL:url];
    //開始
    [downTask resume];
    
    
}

- (IBAction)pause:(UIButton *)sender {
    //暫停下載
    [downTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {//已經下載好的數據
  //定義一個全局變量來接收,在后面需要恢復下載
        saveData = resumeData;
        //安全釋放
        downTask = nil;    
    }];
    
}

//恢復下載
- (IBAction)going:(UIButton *)sender {
    //這里的downtask已經不是之前的downtask了
    //恢復到已經下載的數據
    downTask = [startSession downloadTaskWithResumeData:saveData];
    //繼續任務
    [downTask resume];
    
}


//下載完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    
    NSLog(@"location:%@",location);
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *newPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/01.mp4"];
    NSURL *newURL = [NSURL URLWithString:newPath];
    [manager moveItemAtURL:location toURL:newURL error:nil ];
    
    NSLog(@"newURL:%@",newPath);
    
}

//每下載一個數據包調用一次
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    /*
     bytesWritten   -每次下載的數據包的大小
     totalBytesWritten -已下載的數據
     totalBytesExpectedToWrite  -總數據大小
     */
    
    NSLog(@"bytesWritten %lld , totalBytesWritten  %lld,totalBytesExpectedToWrite %lld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
    //進度條
    float current = (float)totalBytesWritten /totalBytesExpectedToWrite;
    progressView.progress = current;
    
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容