【问题标题】:get the URL for NSData saved in CoreData获取保存在 CoreData 中的 NSData 的 URL
【发布时间】:2017-10-05 17:13:27
【问题描述】:

我正在将 UIImage 保存到 Core Data。所以首先,我将它转换为 NSData,然后保存它。

我需要在图片保存后获取图片的 URL。我这样做是因为我想安排带有附件的本地通知,而唯一的方法,AFAIK,就是使用 URL。

这是我的代码:

//my image:  
var myImage: UIImage?
var imageData: NSData?
    if let image = myImage {
    imageData = UIImageJPEGRepresentation(image, 0.5)! as NSData
}
myEntity.setValue(imageData, forKey: "image")

这就是我应该在通知中添加附件的方式:
UNNotificationAttachment.init(identifier: String, url: URL>, options: [AnyHashable : Any]?)

当用户点击按钮保存图像时,我正在保存图像并手动安排通知。

如果您需要更多信息,请告诉我。

【问题讨论】:

  • 将图片保存到本地,并将其url保存到CoreData
  • UIMagagedDocument 似乎是使用核心数据的 UIDocument 的子类,它以 url 启动以获取上下文。我不是很熟悉,但你可能想研究一下。

标签: ios swift core-data unnotificationattachment usernotificationsui


【解决方案1】:

您无法获取网址。如果您将此属性配置为使用外部存储,那么是的,从技术上讲,可能存在文件 URL。可能是。但是没有记录的方式来获取它,而且无论如何它可能根本不存在——因为外部存储设置不需要 Core Data 使用外部存储,它只是允许它这样做。

如果您没有使用该设置,则永远不会有任何 URL,因为图像被保存为 SQLIte 文件的一部分。

如果您需要图像的文件 URL,请将图像保存到与 Core Data 分开的文件中,并将文件名保存为实体属性。然后文件 URL 就是您保存文件的位置。

【讨论】:

  • 谢谢,汤姆,我明白了。
  • 我正在将Core Data中保存的数据推送到CloudKit,您认为在通知中使用CKAsset的URL是否正确?如果这不是主要问题,我很抱歉。
  • 我几乎没有用过CloudKit,所以不能肯定。
【解决方案2】:

当我遇到同样的挑战时,我如何保存它,然后在实践中获取 URL:

斯威夫特 5:

 func getImageURL(for image: UIImage?) -> URL {
            let documentsDirectoryPath:NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
            let tempImageName = "tempImage.jpg"
            var imageURL: URL?

            if let image = image {

                let imageData:Data = image.jpegData(compressionQuality: 1.0)!
                let path:String = documentsDirectoryPath.appendingPathComponent(tempImageName)
                try? image.jpegData(compressionQuality: 1.0)!.write(to: URL(fileURLWithPath: path), options: [.atomic])
                imageURL = URL(fileURLWithPath: path)
                try? imageData.write(to: imageURL!, options: [.atomic])
            }
            return imageURL!
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多