How to put an image in a Realm database?

前端 未结 2 2003
盖世英雄少女心
盖世英雄少女心 2020-11-28 04:31

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 t

2条回答
  •  醉梦人生
    2020-11-28 05:24

    ProblemSlover's solution updated for Swift 2.2:

    Important Note: the only change is that now stringByAppendingPathComponent has been removed as of Swift 2.1, so you will get an error saying:

    stringByAppendingPathComponent is unavailable: use URLByAppendingPathComponent on NSURL instead.

    Please keep in mind that while it may be annoying, it has been removed for a reason and you should follow apple's recommendation to use NSURL instead. BUT if you wish to proceed with this solution, the fix for Swift 2.1+ is to explicitly cast documentsPath to NSString:

    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) {
        //Explicitly cast to NSString
        let documentsPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString)
        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)
        }
    }
    

提交回复
热议问题