Swift 3 -保存图像到核心数据

时间:2023-01-30 16:31:31

For some reason I can't figure out how to save images to core data and fetch them again. I have a feeling it's something about my types but have a look:

由于某些原因,我无法弄清楚如何将图像保存到核心数据并再次获取它们。我有一种感觉,这是我的类型,但看看:

Swift 3 -保存图像到核心数据

I get my data from an api call to my server. It returns a base64 string. Here is where I get the data:

我从对服务器的api调用中获取数据。它返回一个base64字符串。下面是我得到的数据:

updateAccessTokenOnly(newAccessToken: aToken!)
saveImageToDB(brandName: imageBrandName, image: data! )

Here I save it to my DB:

我把它保存到我的数据库:

func saveImageToDB(brandName: String, image: Data) {
    dropImages(){tableDropped in
        let managedContext = getContext()
        let entity = NSEntityDescription.entity(forEntityName: "CoffeeShopImage", in: managedContext)!
        let CSI = NSManagedObject(entity: entity, insertInto: managedContext)

        CSI.setValue(image, forKey: "image")
        CSI.setValue(brandName, forKey: "brandName")

        do {
            try managedContext.save()
            print("saved!")
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }
    }
}

then to fetch it:

然后获取:

    func getImageFromDB(callback: @escaping (_ image: UIImage)-> ()) {

    let fetchRequest: NSFetchRequest<NSManagedObject> = NSFetchRequest(entityName: "CoffeeShopImage")

    do {
        let searchResults = try getContext().fetch(fetchRequest)

        for images in searchResults {
            print("vi når her ned i get image")
            if (images.value(forKey: "brandName")! as! String == "Baresso"){
                print(images.value(forKey: "brandName")! as! String)

                let image: Data = images.value(forKey: "image")! as! Data
                let decodedimage = UIImage(data: image)

                callback(decodedimage!)

            }
        }
    } catch {
        print("Error with request: \(error)")
    }
}

Full error log:

完整的错误日志:

https://docs.google.com/document/d/1gSXE64Sxtzo81eBSjv4bnBjBnnmG4MX2tuvNtnuJDIM/edit?usp=sharing

https://docs.google.com/document/d/1gSXE64Sxtzo81eBSjv4bnBjBnnmG4MX2tuvNtnuJDIM/edit?usp=sharing

Hope someone can help. Thanks in advance!

希望有人可以帮助你。提前谢谢!

UPDATED

更新

So I uninstalled the app and then the code above worked. However the pictures come out blue? (yes I've checked that the pictures sent from the database are correct).

所以我卸载了应用程序,上面的代码就可以运行了。但是这些照片是蓝色的?(是的,我检查过从数据库发送的图片是否正确)。

Any solution?

有解决方案吗?

Swift 3 -保存图像到核心数据

2 个解决方案

#1


9  

replace

取代

let image: Data = images.value(forKey: "image")! as! Data
let dataDecoded : Data = Data(base64Encoded: image, options: [])!
let decodedimage = UIImage(data: dataDecoded)

with

let image: Data = images.value(forKey: "image")! as! Data
let decodedimage = UIImage(data: image)

Base64 is a way to to convert data to a string. There is no reason to use it here. You already have the data from the database you just want to convert it to a UIImage.

Base64是一种将数据转换为字符串的方法。没有理由在这里使用它。您已经有了来自数据库的数据,您只需将其转换为UIImage。

also change

也发生了变化

let image = data?.base64EncodedData()
saveImageToDB(brandName: imageBrandName, image: image!)

to

saveImageToDB(brandName: imageBrandName, image: data!)

base64EncodedData is turning the data from image data into a utf-8 encoded based64encoded string. There is no reason for that.

base64EncodedData将数据从图像数据转换为utf-8编码的based64encoded字符串。这是没有理由的。

You should get the base64 encoded string from server, convert it to data and then you never need base64 again. Read and write data to your database, and after you read it convert it to a UIImage. Base64 is an encoding method to transfer data. If you are not talking to the server there is no reason to use base64.

您应该从服务器获取base64编码的字符串,将其转换为数据,然后就再也不需要base64了。读取并写入数据到数据库,读取后将其转换为UIImage。Base64是一种传输数据的编码方法。如果不与服务器通信,就没有理由使用base64。

#2


1  

After the suggested corrections from Jon Rose all I needed was to add

在琼恩·罗斯提出的修正建议之后,我需要做的就是补充

.withRenderingMode(.alwaysOriginal)

to where I was showing my picture and the code worked.

到我展示我的照片和代码工作的地方。

#1


9  

replace

取代

let image: Data = images.value(forKey: "image")! as! Data
let dataDecoded : Data = Data(base64Encoded: image, options: [])!
let decodedimage = UIImage(data: dataDecoded)

with

let image: Data = images.value(forKey: "image")! as! Data
let decodedimage = UIImage(data: image)

Base64 is a way to to convert data to a string. There is no reason to use it here. You already have the data from the database you just want to convert it to a UIImage.

Base64是一种将数据转换为字符串的方法。没有理由在这里使用它。您已经有了来自数据库的数据,您只需将其转换为UIImage。

also change

也发生了变化

let image = data?.base64EncodedData()
saveImageToDB(brandName: imageBrandName, image: image!)

to

saveImageToDB(brandName: imageBrandName, image: data!)

base64EncodedData is turning the data from image data into a utf-8 encoded based64encoded string. There is no reason for that.

base64EncodedData将数据从图像数据转换为utf-8编码的based64encoded字符串。这是没有理由的。

You should get the base64 encoded string from server, convert it to data and then you never need base64 again. Read and write data to your database, and after you read it convert it to a UIImage. Base64 is an encoding method to transfer data. If you are not talking to the server there is no reason to use base64.

您应该从服务器获取base64编码的字符串,将其转换为数据,然后就再也不需要base64了。读取并写入数据到数据库,读取后将其转换为UIImage。Base64是一种传输数据的编码方法。如果不与服务器通信,就没有理由使用base64。

#2


1  

After the suggested corrections from Jon Rose all I needed was to add

在琼恩·罗斯提出的修正建议之后,我需要做的就是补充

.withRenderingMode(.alwaysOriginal)

to where I was showing my picture and the code worked.

到我展示我的照片和代码工作的地方。