Saturday, November 21, 2026
HomeiOS Developmentios - Crash when trying to current QLPreviewController

ios – Crash when trying to current QLPreviewController

[ad_1]

I’m making an attempt to current a QLPreviewController for a single UIImage. My preview merchandise is as observe:

last class PreviewItem: NSObject, QLPreviewItem {
    let url: URL

    init(url: URL) {
        self.url = url
    }

    var previewItemURL: URL? {
        url
    }
}

And for my part controller I’ve:

personal var previewItems: [QLPreviewItem] = []

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

func saveImage(picture: UIImage) -> Bool {
    guard let information = picture.jpegData(compressionQuality: 0.8) else { return false }

    let fileName = getDocumentsDirectory().appendingPathComponent("annotate.png")

    guard (strive? information.write(to: fileName)) != nil else { return false }

    return true
}

func getPreviewItem() -> PreviewItem? {
    let imageURL = getDocumentsDirectory().appendingPathComponent("annotate.png")
    let imagePath = (getDocumentsDirectory().appendingPathComponent("annotate.png")).path

    guard FileManager.default.fileExists(atPath: imagePath) else { return nil }

    return PreviewItem(url: imageURL)
}

// MARK: - Information Supply

func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
    1
}

func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
    previewItems[index]
}

// MARK: - Delegate

func previewController(
    _ controller: QLPreviewController,
    editingModeFor previewItem: QLPreviewItem
) -> QLPreviewItemEditingMode {
    .updateContents
}

After I faucet the picture the next perform is invoked:

personal func showEditPhoto(picture: UIImage?) {
    guard let picture = picture, saveImage(picture: picture), let previewItem = getPreviewItem() else { return }
    previewItems.removeAll()
    previewItems.append(previewItem)

    let vc = QLPreviewController()
    vc.delegate = self
    vc.dataSource = self
    vc.currentPreviewItemIndex = 0
    current(vc, animated: true)
}

Nevertheless the app is crashing and I get the next message:

Thread 1: "*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: try and insert nil object from objects[2]"

I’ve debugged the previewItem.previewItemURL?.absoluteString worth and get:

file:///Customers/kekearif/Library/Developer/CoreSimulator/Gadgets/D4003825-4548-4DBA-9B34-FCCC4FF5BD17/information/Containers/Information/Software/9FEBD729-30BD-479A-8D0B-60D379CA050F/Paperwork/annotate.png

So it appears to have discovered the file accurately. What am I doing incorrect right here?

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments