之後就像一千個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