您的位置:首页 > 移动开发 > IOS开发

iOS开发 使用NSURLConnection实现下载文件

2017-07-19 17:18 399 查看
一.下载小文件

1.第一种方法:直接用Data的contentsOf: URL方法

// 下载小文件(方法1)
class func urlConnectionDownloadSmall(_ url: String, success: @escaping (_ data: Data?) -> Swift.Void, fail: (_ error: Error) -> Swift.Void) {
if url.isEmpty {
fail(NSError(domain: "url为空", code: 404, userInfo: [:]))
return
}
do {
let data = try Data(contentsOf: URL(string: url)!)
success(data)
} catch {
fail(error)
}
}

2.第二种方法:使用NSURLConnection发送一个HTTP请求去下载

// 下载小文件(方法2)
class func urlConnectionDownloadSmall(_ url: String, success: @escaping (_ data: Data?) -> Swift.Void, fail: @escaping (_ error: Error) -> Swift.Void) {
if url.isEmpty {
fail(NSError(domain: "url为空", code: 404, userInfo: [:]))
return
}
let request = URLRequest(url: URL(string: url)!)
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) { (response, data, error) in
if let error = error {
fail(error)
} else {
success(data)
}
}
}

3.第三种方法:如果是下载图片,还可以利用SDWebImage框架

二.下载大文件

1.第一种方法:使用NSURLConnectionDataDelegate代理方法

第一步:创建URL和请求

// 下载大文件
func urlConnectionDownload(_ url: String) -> NSURLConnection? {
let request = URLRequest(url: URL(string: url)!)
// 发送异步请求
let connection = NSURLConnection(request: request, delegate: self)
return connection
}

第二步:设置代理NSURLConnectionDataDelegate

第三步:实现代理NSURLConnectionDataDelegate方法

// 接收到响应头信息的时候就会调用(最先调用的方法),只会调用一次
func connection(_ connection: NSURLConnection, didReceive response: URLResponse) {
print("didReceive response")
// 文件的总大小
totalSize = response.expectedContentLength
// 得到的文件名称
fileName = response.suggestedFilename
}

func connection(_ connection: NSURLConnection, didReceive data: Data) {
print("didReceive data")
// 这是拼接数据的方法
fileData.append(data)
print(fileData.count / totalSize)
}

func connectionDidFinishLoading(_ connection: NSURLConnection) {
print("didFinish loading")
if let cache = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last {
let nsCache = cache as NSString
let fullPath = nsCache.appendingPathComponent(fileName!)
do {
try fileData.write(to: URL(fileURLWithPath: fullPath!))
} catch {
print(error)
}
print(fullPath!)
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息