writeToFile不能保存照片

时间:2016-01-20 09:55:14

标签: ios swift nsdata

func fetchFromInternet(){
    let i = Int(DISPATCH_QUEUE_PRIORITY_HIGH.value)
    let que = dispatch_get_global_queue(i, 0)
    dispatch_async(que){
        if let url = NSURL(string: "http://www.hdwallpapers.in/walls/some_are_different-wide.jpg"){
            if let data = NSData(contentsOfURL: url){
                if let image = UIImage(data: data){
                    dispatch_async(dispatch_get_main_queue()){
                        self.spinner.stopAnimating()
                        self.imageContainer.image = image
                        let manager = NSFileManager.defaultManager()
                        var fileUrl = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: .UserDomainMask).first
                        fileUrl = fileUrl?.URLByAppendingPathComponent("photos")
                        do{
                            try manager.createDirectoryAtURL(fileUrl!, withIntermediateDirectories: false, attributes: nil)
                        }
                        catch{}
                        fileUrl = fileUrl?.URLByAppendingPathComponent("photo.jpg")
                        print(fileUrl)

                        if data.writeToFile(String(fileUrl!), atomically: true) {
                            print("saved to file")
                        }
                        else {
                            print("saving failed")
                        }
                    }
                }
            }
        }
    }
}

我的代码有问题。它始终打印"保存失败"。我只是想从互联网上保存照片。我在这里使用一些随机照片。不知道我做错了什么。代码似乎简单而正确。

4 个答案:

答案 0 :(得分:1)

在尝试将文件写入文件夹之前,您有责任确保该文件夹存在。文件保存方法不会为您创建它,如果它不存在则会失败。

使用NSFileManager createDirectoryAtURL: withIntermediateDirectories:attributes:error:

答案 1 :(得分:1)

致电:

data.writeToFile(String(fileUrl!), atomically: true)

应该是:

data.writeToFile(fileUrl!.path, atomically: true)

或者,更好:

data.writeToURL(fileUrl!, atomically: true)

答案 2 :(得分:0)

以下是从Internet下载图像并将其存储到Document目录的完整代码,您也可以访问它。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imageContainer: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        //get image from URL
        if let checkedUrl = NSURL(string: "http://www.hdwallpapers.in/walls/some_are_different-wide.jpg") {
            imageContainer.contentMode = .ScaleAspectFit
            downloadImage(checkedUrl)
        }
    }

    func getDocumentsURL() -> NSURL {
        let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
        return documentsURL
    }

    func fileInDocumentsDirectory(filename: String) -> String {

        let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename)
        return fileURL.path!

    }

    func downloadImage(url: NSURL){
        print("Download Started")
        print("lastPathComponent: " + (url.lastPathComponent ?? ""))
        getDataFromUrl(url) { (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()) { () -> Void in
                guard let data = data where error == nil else { return }
                print(response?.suggestedFilename ?? "")
                print("Download Finished")
                self.imageContainer.image = UIImage(data: data)

                let myImageName = "image.png"
                let imagePath = self.fileInDocumentsDirectory(myImageName)

                //Store that image into Document directory
                if let image = self.imageContainer.image {
                    self.saveImage(image, path: imagePath)
                } else { print("some error message") }

                //Retrive image from document directory
                if let loadedImage = self.loadImageFromPath(imagePath) {
                    print(" Loaded Image: \(loadedImage)")
                } else { print("some error message 2") }
            }
        }
    }

    func getDataFromUrl(url:NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError? ) -> Void)) {
        NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
            completion(data: data, response: response, error: error)
            }.resume()
    }

    func saveImage (image: UIImage, path: String ) -> Bool{

        let pngImageData = UIImagePNGRepresentation(image)
        //let jpgImageData = UIImageJPEGRepresentation(image, 1.0)   // if you want to save as JPEG
        let result = pngImageData!.writeToFile(path, atomically: true)

        return result

    }

    func loadImageFromPath(path: String) -> UIImage? {

        let image = UIImage(contentsOfFile: path)

        if image == nil {

            print("missing image at: \(path)")
        }
        print("Loading image from path: \(path)") // this is just for you to see the path in case you want to go to the directory, using Finder.
        return image

    }
}

答案 3 :(得分:0)

首先,检查一下'数据'和' fileURL'不是零。 在这种情况下,我认为' fileUrl'是你的问题,因为是NSURL。 writeToFile func将String作为输入,因此您需要使用.absoluteString属性。

data.writeToFile(fileUrl!.absoluteString, atomically: true)