之后就像一千个print()
声明,我终于找到了问题!但是,我不知道如何解决它。问题就出在这行:NSFileManager.defaultManager()。createFileAtPath()返回false
NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil)
根据苹果开发者指南,这行代码returns true if the operation was successful or if the item already exists, otherwise false.
此行返回一个false
,我不知道是什么原因,因为代码前面该行似乎没问题。任何人有关于如何解决这个错误的建议?
的代码的其余部分是在这里:
//
// 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.
}
}
你为什么不使用我的代码张贴在你最后的问题? –
该目录是否存在?如果没有,您可能需要创建它。 – jtbandes
请尝试将文件保存在'NSSearchPathDirectory.DocumentDirectory'中。让我知道。 – Nishant