国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

關于NSURLSession的上傳和下載

2019-11-14 20:37:38
字體:
來源:轉載
供稿:網友

關于NSURLsession的上傳和下載

在IOS7.0后,蘋果公司新推出了一個NSURLSession來代替NSURLConnection。NSURLConnection默認是在主線程執行的。而NSURLSession是在其他線程上執行的。本篇主要實現了下載和上傳,比起NSURLConnection更加簡單。線程控制掌握更加清晰。

#PRagma mark - 下載

- (IBAction)DownLoad

{

    //1.URL 

    NSString *urlStr = @"http://she.21cn.com/emotions/mingren/a/2014/0309/15/26645767.shtml";

    NSURL *url = [NSURL URLWithString:urlStr];

    

    //2.NSURLRequest

    NSURLRequest *request = [NSURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:5.0];

    

    //3.NSURLSession

    NSURLSession *session = [NSURLSessionsharedSession];

    

    NSURLSessionDownloadTask *downLoad = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

        if (error) {

            NSLog(@"error = %@",error.localizedDescription);

        }else{

            // location是下載的臨時文件目錄

            NSLog(@"%@", location);

            

            // 如果要保存文件,需要將文件保存至沙盒

            // 1. 根據URL獲取到下載的文件名

            NSString *fileName = [urlStr lastPathComponent];

            

            // 2. 生成沙盒的路徑

            NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

            NSString *path = [docs[0] stringByAppendingPathComponent:fileName];

            NSURL *toURL = [NSURL fileURLWithPath:path];

            

            // 3. 將文件從臨時文件夾復制到沙盒,iOS中所有的文件操作都是使用NSFileManager

            [[NSFileManager defaultManager] copyItemAtURL:location toURL:toURL error:nil];

            

            // 4. 將圖像設置到UIImageView

      

            dispatch_async(dispatch_get_main_queue(), ^{

                UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];

                _imageView.image = image;

            });

        }

    }];

    

//4.因為任務默認是掛起狀態,需要恢復任務(執行任務)

    [downLoad resume];

}

- (IBAction)upLoad

{

    // 0. 判斷imageView是否有內容

    if (_imageView.image == nil) {

        NSLog(@"image view is empty");

        

        return;

    }

    

    // 0. 上傳之前在界面上添加指示符

    UIActivityIndicatorView *indicator = [[UIActivityIndicatorViewalloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

    // 設置位置???

    CGSize size = _imageView.bounds.size;

    indicator.center = CGPointMake(size.width / 2.0, size.height / 2.0);

    

    [self.imageView addSubview:indicator];

    [indicator startAnimating];

    

    // 1. URL

    NSString *urlStr = @"http://192.168.3.251/uploads/123.jpg";

    NSURL *url = [NSURL URLWithString:urlStr];

    

    // 2. Request -> PUT,request的默認操作是GET

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:5.0f];

    request.HTTPMethod = @"PUT";

    

    // *** 設置網絡請求的身份驗證! ***

    // 1> 授權字符串

    NSString *authStr = @"admin:123456";

    // 2> BASE64的編碼,避免數據在網絡上以明文傳輸

    // iOS,僅對NSData類型的數據提供了BASE64的編碼支持

    NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];

    NSString *encodeStr = [authData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];

    

    NSString *authValue = [NSString stringWithFormat:@"Basic %@", encodeStr];

    [request setValue:authValue forHTTPHeaderField:@"Authorization"];

    

    // 3. Session

    NSURLSession *session = [NSURLSessionsharedSession];

    

    // 4. UploadTask

    NSData *imageData = UIImageJPEGRepresentation(_imageView.image, 0.75);

    NSURLSessionUploadTask *upload = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        

        // 上傳完成后,data參數轉換成string就是服務器返回的內容

        NSString *str = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];

        NSLog(@"OK -> %@", str);

        

        if (error != nil) {

            NSLog(@"ERROR -> %@", error.localizedDescription);

        } else {

            

        }

        

        [NSThreadsleepForTimeInterval:5.0f];

        

        dispatch_async(dispatch_get_main_queue(), ^{

            [indicator stopAnimating];

            

            [indicator removeFromSuperview];

        });

    }];

    

    [upload resume];

}

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 贵州省| 邹城市| 东乡| 肇东市| 安化县| 三台县| 师宗县| 乐东| 来凤县| 嘉祥县| 靖州| 合川市| 定远县| 阜新市| 杂多县| 延津县| 宁蒗| 连城县| 天水市| 太湖县| 连州市| 尖扎县| 尚志市| 澄迈县| 广河县| 包头市| 淳安县| 龙泉市| 砀山县| 页游| 融水| 广宁县| 夏津县| 开阳县| 望江县| 江口县| 巴马| 娱乐| 福安市| 平阴县| 万源市|