URL文件的大小根据NSURLConnection的 - 斯威夫特(URL File Size Wi

2019-10-21 02:55发布

我试图下载前得到URL的文件大小

这里是OBJ-C代码

    NSURL *URL = [NSURL URLWithString:"ExampleURL"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    [request setHTTPMethod:@"HEAD"];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error: nil];
    long long size = [response expectedContentLength];

这里是银行代码

var url:NSURL = NSURL(string: "ExmapleURL")
                var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
                request.HTTPMethod = "HEAD"
                var response = NSHTTPURLResponse()
                NSURLConnection.sendSynchronousRequest(request, returningResponse: &response , error: nil)

但我有错误这里

NSURLConnection.sendSynchronousRequest(request, returningResponse: &response , error: nil)

'NSHTTPURLResponse' is not identical to 'NSURLResponse?'

我错过在这里迅速什么?

Answer 1:

响应参数有类型

AutoreleasingUnsafeMutablePointer<NSURLResponse?>

这意味着你可以通过一个可选的地址NSURLResponse作为参数:

var response : NSURLResponse?
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response , error: nil)

然后,您可以有条件地转换为返回的响应NSHTTPURLResponse

if let httpResponse = response as? NSHTTPURLResponse {
    println(httpResponse.expectedContentLength)
}

请注意,您应该检查返回值sendSynchronousRequest()这是nil ,如果没有连接可以作出。

此外,还建议调用仅从一个单独的线程此方法(或使用sendAsynchronousRequest()代替),因为它可能需要一段时间来建立连接-使用蜂窝网络时特别-和主线程否则会被阻塞。



Answer 2:

斯威夫特4解决方案:

func fetchContentLength(for url: URL, completionHandler: @escaping (_ contentLength: Int64?) -> ()) {

    var request = URLRequest(url: url)
    request.httpMethod = "HEAD"

    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    guard error == nil, let response = response as? HTTPURLResponse, let contentLength = response.allHeaderFields["Content-Length"] as? String else {
        completionHandler(nil)
        return
    }
        completionHandler(Int64(contentLength))
    }

        task.resume()
}

// Usage:

let url = URL(string: "https://s3.amazonaws.com/x265.org/video/Tears_400_x265.mp4")!

fetchContentLength(for: url, completionHandler: { contentLength in
    print(contentLength ?? 0)
})


文章来源: URL File Size With NSURLConnection - Swift