2016-04-26 41 views
0

下面的代碼是可用的。圖像已成功保存在文檔目錄中,但問題只是第一次collectionViewController可以成功加載路徑的圖像。我必須刪除所有圖像存儲新的圖像,否則將顯示錯誤消息Swift - 除第一次使用外文件路徑不可用

"fatal error: unexpectedly found nil while unwrapping an Optional value".

因爲路徑是不可用的,readnsdata = NSData(contentsOfFile: filepath)!會導致錯誤。

我不知道爲什麼只有第一次它可以工作。

path : "/var/mobile/Containers/Data/Application/29306029-BDCF-4BEA-93A6-D5626CBAAA90/Documents/x.jpg"

func writeNSDataToDisk(imageData:NSData){ 

    let myindex = imgPathArray.count 
    let fileName = "\(self.imgPathArray.count)" 
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) 
    let docs: String = paths[0] as String 
    let filepath: String = (docs as NSString).stringByAppendingPathComponent("\(fileName).jpg")   
    let test = imageData.writeToFile(filepath, atomically: true) 
    if test { 
     self.imgPathArray.insert(filepath, atIndex: myindex) 
     print("The picture \(fileName).jpg is been saved.") 
     self.readORwriteList(true)//write list to txt file 
    } 
    print(self.imgPathArray) 
} 


func readNSDataFromDisk(fileIndex:Int) -> NSData{ 
    let checkValidation = NSFileManager.defaultManager() 
    var readnsdata = NSData() 
    if (fileIndex <= self.imgPathArray.count) { 
     let filepath = self.imgPathArray[fileIndex] 
     if (checkValidation.fileExistsAtPath(filepath)){ 
      print("File is available") 
      print("load \(fileIndex).jpg,filepath is \(filepath)") 
      readnsdata = NSData(contentsOfFile: filepath)! 
      if readnsdata.length != 0 { 
       getImageProperties(readnsdata) 
      } 
     } 
     else{ 
      print("File is not available!!!") 
     } 
    } 
    return readnsdata 
} 

的解決我的問題:

不是存儲絕對文件路徑的,我的名字在一個正常做法的文件,並通過自己的名字搜索。沒有必要存儲路徑。

現在,每次運行應用程序時,文件的URL都是相對於Documents目錄URL構建的。

感謝

回答

2

首先是旁註。 Apple的docs特別建議不要在此處使用fileExistsAtPath

NOTE

Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It’s far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed.

嘗試更換此...

if (checkValidation.fileExistsAtPath(filepath)){ 
    print("File is available") 
    print("load \(fileIndex).jpg,filepath is \(filepath)") 
    readnsdata = NSData(contentsOfFile: filepath)! 
    if readnsdata.length != 0 { 
     getImageProperties(readnsdata) 
    } 
} 
else{ 
    print("File is not available!!!") 
} 

...這... ...

do { 
    readnsdata = try NSData(contentsOfFile: filepath, options: .DataReadingMappedIfSafe) 
    if readnsdata.length != 0 { 
     getImageProperties(readnsdata) 
    } 
} 
catch let e { 
    print("Couldn't read file at \(filepath) because \(e)") 
} 

這種方法給你,你不必猜測正在尋找的信息。只需運行你的代碼,看看當NSData初始化器拋出時會發生什麼! :)


[更新:題外話意見]

雖然這是一個很好的習慣,不要灑長的方法有回報,有沒有很多怎麼回事。就個人而言,我認爲沒有臨時變量readnsdata,代碼更具可讀性。這樣,imo,快樂路徑和默認返回值在一讀時都很清楚:

func readNSDataFromDisk2(fileIndex:Int) -> NSData{ 
    if (fileIndex <= self.imgPathArray.count) { 
     let path = self.imgPathArray[fileIndex] 
     do { 
      let data = try NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe) 
      if data.length != 0 { 
       getImageProperties(data) 
      } 
      return data 
     } 
     catch let e { 
      print("Couldn't read file at \(path) because \(e)") 
     } 
    } 
    return NSData() 
} 
+0

我從您的回答中受益匪淺。希望我的代碼風格變得更加清晰:p – Jinny

0

取代readnsdata = NSData(contentsOfFile: filepath)!readnsdata = NSData(contentsOfFile: filepath)?。希望這會有所幫助:)

相關問題