NSFileManager.defaultManager (). CreateFileAtPath () returns false

After sort of thousands of print()operators, I finally identified the problem! However, I am not sure how to fix this. The problem is the line:

NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil)

According to Apple Developer Guide, this line of code returns true if the operation was successful or if the item already exists, otherwise false.

This line returns false, and I'm not quite sure why, since the code preceding the line seems to be all right. Anyone have any suggestions for fixing this error?

The rest of the code is here:

//
//  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.PicturesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
                    print(paths)
                    if paths.count > 0 {
                        documentsDirectory = paths[0] as? String
                        let savePath = documentsDirectory! + "/bach.jpg"

                        print(NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil))

                        if NSFileManager.defaultManager().fileExistsAtPath(savePath) {
                            print("file available")
                        }
                        else {
                            print("file not available")
                        }



                        self.image.image = UIImage(contentsOfFile: savePath)
                    }
                }
            }
        })
        task!.resume()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
+4
source share
1 answer
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


            // 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 {
                    print(data.length)
                    // get your caches directory URL
                    let cachesDirectory = try! NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
                    // create your local file url by appending your url last path component
                    let fileUrl = cachesDirectory.URLByAppendingPathComponent(url.lastPathComponent!)
                    // save downloaded data to disk
                    if data.writeToURL(fileUrl, atomically: true) {
                        print(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.
    }
}

Note that you will need to edit your layer as follows:

enter image description here

+3
source

Source: https://habr.com/ru/post/1606118/


All Articles