ios - 图片不显示可能是因为没有保存在文件路径中

标签 ios xcode swift

所以我目前正在尝试保存图像并在应用程序中显示该图像。但是,图像未显示。不知道是图片保存不正确还是其他问题。当我添加行 self.image.image = bach 时,图像会正确显示。但是,当我注释掉该行时,图像不显示。但是,我认为,它应该被显示,因为我将数据保存在变量 savePath 中。因此,self.image.image = UIImage(named: savePath) 应该会导致我的应用显示正确的图像。关于如何解决此问题的任何建议?

代码如下:

//
//  ViewController.swift
//  Downloading An Image From The Web
//
//  Created by Jae Hyun Kim on 9/6/15.
//  Copyright © 2015 Jae Hyun Kim. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var image: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let url = NSURL(string: "http://7-themes.com/data_images/out/3/6776407-beautiful-scenery-pictures.jpg")
        let urlRequest = NSURLRequest(URL: url!)

        let task = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) -> Void in
            if error != nil {
                print(error)
            }
            else {
                if let bach = UIImage(data: data!) {
                    //self.image.image = bach
                    let documentsDirectory:String?
                    let paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentationDirectory, NSSearchPathDomainMask(), true)
                    if paths.count > 0 {
                        documentsDirectory = paths[0] as? String
                        let savePath = documentsDirectory! + "/bach.jpg"
                        NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil)
                        self.image.image = UIImage(named: savePath)
                    }
                }
            }
        })
        task!.resume()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

最佳答案

问题是 UIImage(named:) 用于您资源中的图像。如果你想从磁盘加载图像,你需要使用 UIImage(contentsOfFile:)。

像这样尝试:

class ViewController: UIViewController {
@IBOutlet weak var image: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        let url = NSURL(string: "http://7-themes.com/data_images/out/3/6776407-beautiful-scenery-pictures.jpg")!
        let urlRequest = NSURLRequest(URL: url)

        let task = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) -> Void in


            // you should always do it from the main queue otherwise you will experience a big delay when trying to display your image
            dispatch_async(dispatch_get_main_queue()) {
                // unwrap your data
                if let data = data {
                    println(data.length)
                    // get your document directory URL
                    let documentDirectory = NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true, error: nil)!
                    // create your local file url by appending your url last path component
                    let fileUrl = documentDirectory.URLByAppendingPathComponent(url.lastPathComponent!)
                    // save downloaded data to disk
                    if data.writeToURL(fileUrl, atomically: true) {
                        println(true)
                        // load your saved image from disk
                        self.image.image = UIImage(contentsOfFile: fileUrl.path!)
                    }

                }
            }

        })
        task.resume()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

关于ios - 图片不显示可能是因为没有保存在文件路径中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32419921/

相关文章:

ios - Flutter:由于集成了 firebase 和 Admob,无法构建 iOS 应用程序

ios - iPhone Mapkit 中的图像

ios - CLLocationManager.requestLocation() 大约需要 10 秒

ios - 根据屏幕大小更改节点定位 Swift/Sprite Kit

ios - 如何在旧的 iOS 设备上使用 ARKit?

swift - 通用链接未重定向到我的 ios 应用程序

swift - 为什么我的 Playground 在 NSRange() 上崩溃

ios - 当单元格在 View 外部时,ClipsToBounds重置

ios - 用于显示配置文件 (.mobileprovision) 文件内容的工具?

iphone - iOS:如何链接正在开发的App Store链接