通过拖放沙箱验证网址

时间:2017-10-25 12:14:24

标签: macos swift3 drag-and-drop appstore-sandbox nspasteboard

考虑到file access in a sandboxed osx app with swift,它是否与通过Finder或其他应用程序提供的网址相同?

因为没有NSOpenPanel调用来提供文件夹访问,如本例所示,只是网址 - 我认为文件夹访问是隐含的,因为用户从源/桌面“文件夹”拖动文件与通过打开的隐式选择非常相同对话框。

我还没有开始沙盒迁移,但想验证我的想法是否准确,但这是一个候选例程在沙盒模式下工作:

func performDragOperation(_ sender: NSDraggingInfo!) -> Bool {
    let pboard = sender.draggingPasteboard()
    let items = pboard.pasteboardItems

    if (pboard.types?.contains(NSURLPboardType))! {
        for item in items! {
            if let urlString = item.string(forType: kUTTypeURL as String) {
                self.webViewController.loadURL(text: urlString)
            }
            else
            if let urlString = item.string(forType: kUTTypeFileURL as String/*"public.file-url"*/) {
                let fileURL = NSURL.init(string: urlString)?.filePathURL
                self.webViewController.loadURL(url: fileURL!)
            }
            else
            {
                Swift.print("items has \(item.types)")
            }
        }
    }
    else
    if (pboard.types?.contains(NSPasteboardURLReadingFileURLsOnlyKey))! {
        Swift.print("we have NSPasteboardURLReadingFileURLsOnlyKey")
    }
    return true
}

因为没有对URL执行操作或抛出错误。

1 个答案:

答案 0 :(得分:0)

是的,文件访问是隐式的。由于沙盒实现的文档很少,并且有很多错误,因此您需要解决URL和文件名。该视图应在初始化时为这两种类型注册。代码在Objective-C中,但API应该相同。

    [self registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, NSURLPboardType, nil]];

然后执行performDragOperation:

- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
    BOOL dragPerformed = NO;
    NSPasteboard *paste = [sender draggingPasteboard];
    NSArray *typesWeRead = [NSArray arrayWithObjects:NSFilenamesPboardType, NSURLPboardType, nil];
    //a list of types that we can accept
    NSString *typeInPasteboard = [paste availableTypeFromArray:typesWeRead];

    if ([typeInPasteboard isEqualToString:NSFilenamesPboardType]) {
        NSArray *fileArray = [paste propertyListForType:@"NSFilenamesPboardType"];
        //be careful since this method returns id.  
        //We just happen to know that it will be an array. and it contains strings.
        NSMutableArray *urlArray = [NSMutableArray arrayWithCapacity:[fileArray count]];
        for (NSString *path in fileArray) {
            [urlArray addObject:[NSURL fileURLWithPath:path]];
        }
        dragPerformed = //.... do your stuff with the files;
    } else if ([typeInPasteboard isEqualToString:NSURLPboardType]) {
        NSURL *droppedURL = [NSURL URLFromPasteboard:paste];
        if ([droppedURL isFileURL]) {
            dragPerformed = //.... do your stuff with the files;
        }
    }
    return dragPerformed;
}