2016-09-27 74 views
-2

我已將Swift 2.2代碼轉換爲Swift 3.0,但出現以下錯誤。Swift 3.0轉換錯誤

open func saveToPath(_ path: String, format: ImageFormat, compressionQuality: Double) -> Bool 
{ 
    if let image = getChartImage(transparent: format != .jpeg) { 
     var imageData: Data! 
     switch (format) 
     { 
     case .png: 
      imageData = NSUIImagePNGRepresentation(image) 
      break 

     case .jpeg: 
      imageData = NSUIImageJPEGRepresentation(image, CGFloat(compressionQuality)) 
      break 
     } 

     let url = NSURL(string: path) 
     return imageData.write(to: url as! URL, options: true) 
    } 
    return false 
} 

錯誤:

無法將類型的值 '布爾' 預期參數類型 'data.writeOptions'(又名 'NSData.writingOptions'))

什麼問題用這個代碼?

+0

這種方法已經改變了:https://developer.apple.com/reference/foundation/nsdata/1410595-write – Moritz

+0

此外,你投給NSURL網址,但您應該直接使用網址。 – Moritz

+0

將'[]'傳遞給選項而不是'true'。 – Majster

回答

1

下面兩行需要修復:

let url = NSURL(string: path) 
return imageData.write(to: url as! URL, options: true) 
  1. 使用URL,不NSURL
  2. 使用正確的初始化程序將文件路徑字符串轉換爲文件URL。
  3. 將適當的值傳遞給options參數。

固定的代碼應該是這樣的:

let url = URL(fileURLWithPath: path) 
return imageData.write(to: url, options: .atomic)