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
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)
}
}