Search code examples
swiftmacoselectronnsurlshare-extension

how to convert NSUrl into local path url in swift


In my share extension that is built with electron app I am having trouble getting the shared path as simple local path url from nsurl as I am very new to Swift .

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

when I try this line of code I am getting error as follows: Value of type 'NSSecureCoding' has no member 'path'

is there any alternative way of getting shared path as url so I can save to shared container

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)
    }

thank you in advance!


Solution

  • You have to create the URL from the data representation and it's highly recommended to handle the error

    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)
    }
    

    However if the passed URL is already a file system URL you can use it directly.