【发布时间】:2017-10-19 16:51:44
【问题描述】:
我正在学习斯坦福的 iOS 开发课程,我将课程中运行良好的示例代码复制到了我的 Xcode 中。该视图只是不显示 url 图像,我已经将 Allow Arbitrary Loads in info 设置为“yes”。屏幕上没有出现错误,但视图没有显示任何内容。
class ImageViewController: UIViewController
{
var imageURL: URL? {
didSet {
image = nil
if view.window != nil {
fetchImage()
}
}
}
private func fetchImage() {
if let url = imageURL {
let urlContents = try? Data(contentsOf: url)
if let imageData = urlContents {
image = UIImage(data: imageData)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
imageURL = DemoURL.stanford // for demo/testing purposes only
//This is the url image. It is in another swift file,the address is ( static let stanford = URL(string: "http://stanford.edu/about/images/intro_about.jpg",) I can open it in safari.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if image == nil { // we're about to appear on screen so, if needed,
fetchImage() // fetch image
}
}
fileprivate var imageView = UIImageView()
private var image: UIImage? {
get {
return imageView.image
}
set {
imageView.image = newValue
imageView.sizeToFit()
// careful here because scrollView might be nil
// (for example, if we're setting our image as part of a prepare)
// so use optional chaining to do nothing
// if our scrollView outlet has not yet been set
}
}
}
提前致谢。
【问题讨论】:
-
下载图片的代码在哪里?
-
我会通过 URLSession 获取,而不是从 Data 获取,因为您可以检查响应以查看是否有错误,statusCode 在这样的?