如何在Swift中将NSURL转换为本地路径URL

huangapple go评论70阅读模式
英文:

how to convert NSUrl into local path url in swift

问题

在我的使用 Electron 应用程序构建的共享扩展中,我在将 NSURL 转换为简单的本地路径 URL 时遇到了问题,因为我对 Swift 很陌生。

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

当我尝试这行代码时,我收到以下错误:
类型 'NSSecureCoding' 的值没有成员 'path'

是否有其他获取共享路径作为 URL 的替代方法,以便我可以保存到共享容器?

override func didSelectPost() {
    // 执行发布操作
    // 操作完成后(可能是异步的),服务应通知成功或失败,以及实际共享的项目
    let inputItem = self.extensionContext!.inputItems[0] as! NSExtensionItem
    
    if let attachments = inputItem.attachments {
        // 创建一个字符串来保存URL
        var urlsString = ""

        // 遍历附件
        for attachment in attachments {
            // 检查附件是否是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)
                }
            }
        }
        
        // 将URL写入文件
        let fileManager = FileManager.default
        guard let groupContainerURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "share.group") else {
            // 无法访问应用程序组容器
            return
        }
        let fileURL = groupContainerURL.appendingPathComponent("sharedUrls.txt")
        do {
            try urlsString.write(to: fileURL, atomically: true, encoding: .utf8)
            // 文件成功写入
        } catch {
            // 写入文件时发生错误
            print("Error writing file: \(error)")
        }
    }
    
    self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}

提前感谢您!


<details>
<summary>英文:</summary>

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 &#39;NSSecureCoding&#39; has no member &#39;path&#39;**


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 = &quot;&quot;
          
          // Loop through the attachments
          for attachment in attachments {
              // Check if the attachment is a URL
              if attachment.hasItemConformingToTypeIdentifier(&quot;public.file-url&quot;) {
                  attachment.loadItem(forTypeIdentifier: &quot;public.file-url&quot; 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: &quot;share.group&quot;) else {
              // Unable to access the application group container
              return
          }
          let fileURL = groupContainerURL.appendingPathComponent(&quot;sharedUrls.txt&quot;)
          do {
              try urlsString.write(to: fileURL, atomically: true, encoding: .utf8)
              // File successfully written
          } catch {
              // Error occurred while writing the file
              print(&quot;Error writing file: \(error)&quot;)
          }
      }
      
    self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
thank you in advance!


</details>


# 答案1
**得分**: 1

你需要根据数据表示创建URL,并强烈建议处理错误。

```swift
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,你可以直接使用它。

英文:

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

attachment.loadItem(forTypeIdentifier: &quot;public.file-url&quot; 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.

huangapple
  • 本文由 发表于 2023年6月22日 14:28:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529106.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定