【问题标题】:xcode view doesn't show url imagexcode 视图不显示 url 图片
【发布时间】: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 在这样的?

标签: ios swift image url


【解决方案1】:

来自 DemoURL.swift 的 URL 不存在...例如,您可以在 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")

【讨论】:

    【解决方案2】:

    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,苹果iOS9以后要https。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      相关资源
      最近更新 更多