美文网首页
[iOS]获取网络文件大小

[iOS]获取网络文件大小

作者: PlutoMa | 来源:发表于2016-12-05 15:46 被阅读230次

    今天记录一下根据已知的图片、音频或视频等网络文件的地址,来获取文件的大小

    - (void)getUrlFileLength:(NSString *)url
    {
        url = [[NSString alloc] initWithData:[[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] dataUsingEncoding:NSUTF8StringEncoding] encoding:NSUTF8StringEncoding];
        NSMutableURLRequest *mURLRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
        [mURLRequest setHTTPMethod:@"HEAD"];
        mURLRequest.timeoutInterval = 5.0;
        
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:mURLRequest];
        [dataTask resume];
    }
    
    -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
    {
        NSDictionary *dict = [(NSHTTPURLResponse *)response allHeaderFields];
        NSNumber *length = [dict objectForKey:@"Content-Length"];
        [dataTask cancel];
        NSLog(@"%@", length);
    }
    
    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
    didCompleteWithError:(nullable NSError *)error {
        NSLog(@"%@", error);
    }
    

    相关文章

      网友评论

          本文标题:[iOS]获取网络文件大小

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