QLPreviewView cannot display quicklook preview in sandbox
I am using QLPreviewView to show a preview in an application. Without the sandbox, this works well, but as soon as you change the app to sandbox, the preview cannot be displayed.
I found an error in the console: QuickLookUIHelpe(20786) deny file-read-data XXX.
I used security bookmarks and com.apple.security.files.user-selected.read-write to give access to the user's home directory, then
[allowedURL startAccessingSecurityScopedResource];
self.myPreiviewItem.myURL = fileURL;
self.myQLPreviewView.previewItem = self.myPreiviewItem;
[self.myQLPreviewView refreshPreviewItem];
[allowedURL stopAccessingSecurityScopedResource];
with these, I can delete the files in the user's home directory, but the QLPreviewView cannot work. I don't know what is the difference between these two scenes, does the QLPreviewView need more for sandboxing?
If I add com.apple.security.files.downloads.read-only to the file, the files in Downloads can be viewed, but other files in the user's home directory cannot be viewed.
source to share
Finally I found a solution!
refreshPreviewItem
is an asynchronous call, so before the Mac finishes loading the preview, the following api stopAccessingSecurityScopedResource
will immediately disable access, resulting in the Mac unable to load the preview successfully.
so the solution is: do NOT call stopAccessingSecurityScopedResource
here, keep the access right available until you need the QL preview function, and then call stopAccessingSecurityScopedResource
there, for example when the window is closed.
source to share
I ran into this, or at least a similar problem a while ago (in Mavericks).
This is why I started asking users to access the parent folders of the files they want to view. Feel free to watch me as I do this in this app of mine , version 1.1 at the time of this writing. Just go to Chikoo -> Preferences ... -> Folder Access. Here are two screenshots:
I confess that this is not a very good solution. This is the compromise I came up with to solve this problem.
source to share