我正在学习斯坦福大学的iOS开发课程,并将我在课程中完美运行的示例代码复制到我的Xcode中。该视图不显示网址图片,我已将“允许任意负载信息”设置为"是"。屏幕上没有显示错误,但视图没有显示任何内容。
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
}
}
}
提前致谢。
答案 0 :(得分:0)
来自DemoURL.swift的网址不存在......例如,你可以在DemoURL.swift中写一下:
static let stanford = URL(string:"http://upload.wikimedia.org/wikipedia/commons/thumb/c/cd/Stanford_Oval_May_2011_panorama.jpg/800px-Stanford_Oval_May_2011_panorama.jpg")
答案 1 :(得分:0)
1)不要使用同步通话:
见: https://developer.apple.com/documentation/foundation/nsdata/1407864-init
2)以这种方式使用NSURL会话:
let myURL = URL(string: "https: ......")
let session = URLSession.shared
let task = session.dataTask(with: myURL!) { (data, resp, err) in
var statusCode: NSInteger = 0
if let httpResponse : HTTPURLResponse = resp as? HTTPURLResponse{
statusCode = httpResponse.statusCode
}
if let data = data, statusCode == 200{
if let img = UIImage(data: data){
// use your image...
}
}
}
3)不要使用http,Apple要求https,因为ios9。