Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

ios - How to put an image in a Realm database?

I'm writing an iOS application using Swift 2 and I would like to save profile picture of an account locally in a Realm database. I can't find any documentation or people talking about that.

Is it possible? And how?

May be is it bad to do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can store images as NSData. Given you have the URL of an image, which you want to store locally, here is a code snippet how that can be achieved.

class MyImageBlob {
    var data: NSData?
}

// Working Example
let url = NSURL(string: "http://images.apple.com/v/home/cb/images/home_evergreen_hero_iphone_medium.jpg")!
if let imgData = NSData(contentsOfURL: url) {
    var myblob = MyImageBlob()
    myblob.data = imgData 

    let realm = try! Realm()
    try! realm.write {
        realm.add(myblob)
    }
}

May be it is a bad idea to do that?

The rule is simple: If the images are small in size, the number of images is small and they are rarely changed, you can stick with storing them in the database.

If there is a bunch images, you are better off writing them directly to the file system and just storing the path of the image in the database.

Here is how that can be done:

class MyImageStorage{
    var imagePath: NSString?
}

let url = NSURL(string: "http://images.apple.com/v/home/cb/images/home_evergreen_hero_iphone_medium.jpg")!
if let imgData = NSData(contentsOfURL: url) {
    // Storing image in documents folder (Swift 2.0+)
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    let writePath = documentsPath?.stringByAppendingPathComponent("myimage.jpg")

    imgData.writeToFile(writePath, atomically: true)

    var mystorage = MyImageStorage()
    mystorage.imagePath = writePath

    let realm = try! Realm()
    try! realm.write {
         realm.add(mystorage)
    }
}

Please note: Both code samples are not reliable methods for downloading images since there are many pitfalls. In real world apps / in production, I'd suggest to use a library intended for this purpose like AFNetworking or AlamofireImage.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...