我正在開發一款應用程序,允許用戶使用PhotoKit編輯照片。我以前曾將編輯過的照片保存爲JPEG格式的磁盤。我想避免轉換爲JPEG,並已執行修改,以此來做到這一點。它適用於使用相機拍攝的照片,但如果您嘗試編輯屏幕截圖,PHPhotoLibrary.sharedPhotoLibrary().performChanges
模塊將失敗並記錄The operation couldn’t be completed. (Cocoa error -1.)
。我不知道爲什麼這會導致performChanges塊失敗,我在這裏做了什麼錯誤?無法編輯截圖,performChanges塊失敗
我創建了一個演示問題的sample app available to download,並且我在下面包含了相關的代碼。該應用會嘗試編輯照片庫中最新的照片。如果成功,它將提示訪問來編輯照片,否則什麼都不會發生,你會看到控制檯日誌。要重現此問題,請執行截圖,然後運行該應用程序。
當前的代碼,用截屏的工作原理:
let jpegData: NSData = outputPhoto.jpegRepresentationWithCompressionQuality(0.9)
let contentEditingOutput = PHContentEditingOutput(contentEditingInput: self.input)
var error: NSError?
let success = jpegData.writeToURL(contentEditingOutput.renderedContentURL, options: NSDataWritingOptions.AtomicWrite, error: &error)
if success {
return contentEditingOutput
} else {
return nil
}
替換代碼,導致截圖失敗:
let url = self.input.fullSizeImageURL
let orientation = self.input.fullSizeImageOrientation
var inputImage = CIImage(contentsOfURL: url)
inputImage = inputImage.imageByApplyingOrientation(orientation)
let outputPhoto = createOutputImageFromInputImage(inputImage)!
let originalImageData = NSData(contentsOfURL: self.input.fullSizeImageURL)!
let imageSource = CGImageSourceCreateWithData(originalImageData, nil)
let dataRef = CFDataCreateMutable(nil, 0)
let destination = CGImageDestinationCreateWithData(dataRef, CGImageSourceGetType(imageSource), 1, nil) //getType automatically selects JPG, PNG, etc based on original format
struct ContextStruct {
static var ciContext: CIContext? = nil
}
if ContextStruct.ciContext == nil {
let eaglContext = EAGLContext(API: .OpenGLES2)
ContextStruct.ciContext = CIContext(EAGLContext: eaglContext)
}
let cgImage = ContextStruct.ciContext!.createCGImage(outputPhoto, fromRect: outputPhoto.extent())
CGImageDestinationAddImage(destination, cgImage, nil)
if CGImageDestinationFinalize(destination) {
let contentEditingOutput = PHContentEditingOutput(contentEditingInput: self.input)
var error: NSError?
let imageData: NSData = dataRef
let success = imageData.writeToURL(contentEditingOutput.renderedContentURL, options: .AtomicWrite, error: &error)
if success {
//it does succeed
return contentEditingOutput
} else {
return nil
}
}
我已經記錄了一個蘋果的錯誤。這個錯誤也存在於iOS 9和10中。顯然不是他們要解決的高優先級。 – jjxtra