首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >URL会话保存图像

URL会话保存图像
EN

Stack Overflow用户
提问于 2020-03-03 05:14:44
回答 1查看 103关注 0票数 0

快速问答。我想从网址中提取下载的图像,并将其保存到UI图像。

我该怎么做呢?

代码语言:javascript
复制
fileprivate func beginDownload() {

        let url = URL(string: "URL")!

        let configuration = URLSessionConfiguration.default
        let operationQueue = OperationQueue()
        let urlSession = URLSession(configuration: configuration, delegate: self, delegateQueue: operationQueue)

        let downloadTask = urlSession.downloadTask(with: url)

        downloadTask.resume()
}

以下是我的URL会话协议存根:

代码语言:javascript
复制
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        print(totalBytesWritten, totalBytesExpectedToWrite)

    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {

        print("Finished dowloading file")
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-03 05:40:40

您需要从委托方法urlSession(_:downloadTask:didFinishDownloadingTo:)中创建的下载location加载图像

代码语言:javascript
复制
class Request: NSObject {

    func getPicture() {
        let url = URL(string: "https://media.tractorsupply.com/is/image/TractorSupplyCompany/1305371?$456$")!
        let session = URLSession(configuration: .default, 
                                 delegate: self, 
                                 delegateQueue: nil)
        session.downloadTask(with: url).resume()
    }

}

extension Request: URLSessionDownloadDelegate {

    func urlSession(_ session: URLSession, 
                    downloadTask: URLSessionDownloadTask, 
                    didFinishDownloadingTo location: URL) {
        guard let data = try? Data(contentsOf: location), 
              let image = UIImage(data: data) else { return }
        print(image)
    }

}

Request().getPicture()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60496764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档