electron 如何在Swift中将NSUrl转换为本地路径url

x4shl7ld  于 2023-06-27  发布在  Electron
关注(0)|答案(1)|浏览(173)

在我用electron app构建的共享扩展中,我很难从nsurl中获取共享路径作为简单的本地路径url,因为我对Swift非常陌生。

let url = URL(string: nsurl!.path)

当我尝试这行代码时,我得到了如下错误:类型'NSSecureCoding'的值没有成员'path'
是否有任何替代方法获取共享路径作为url,以便我可以保存到共享容器

override func didSelectPost() {
        // Perform the post operation
        // When the operation is complete (probably asynchronously), the service should notify the success or failure as well as the items that were actually shared
        let inputItem = self.extensionContext!.inputItems[0] as! NSExtensionItem
        
        if let attachments = inputItem.attachments {
              // Create a string to hold the URLs
              var urlsString = ""
              
              // Loop through the attachments
              for attachment in attachments {
                  // Check if the attachment is a URL
                  if attachment.hasItemConformingToTypeIdentifier("public.file-url") {
                      attachment.loadItem(forTypeIdentifier: "public.file-url" as String, options: nil) { (nsurl, error) in
                          let url = URL(string: nsurl!.path)
                      }
                  }
              }
              
              // Write the URLs to the file
              let fileManager = FileManager.default
              guard let groupContainerURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "share.group") else {
                  // Unable to access the application group container
                  return
              }
              let fileURL = groupContainerURL.appendingPathComponent("sharedUrls.txt")
              do {
                  try urlsString.write(to: fileURL, atomically: true, encoding: .utf8)
                  // File successfully written
              } catch {
                  // Error occurred while writing the file
                  print("Error writing file: \(error)")
              }
          }
          
        self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
    }

提前感谢!

ffvjumwh

ffvjumwh1#

您必须从数据表示创建URL,强烈建议您处理错误

attachment.loadItem(forTypeIdentifier: "public.file-url" as String, options: nil) { (data, error) in
     if let error { print(error); return } 
     guard let fileUrl = URL(dataRepresentation: data, relativeTo: nil) else { return }
     let url = URL(fileURLWithPath: fileUrl.path)
}

但是,如果传递的URL已经是文件系统URL,则可以直接使用它。

相关问题