Storing images locally on an iOS device

前端 未结 3 1039
别跟我提以往
别跟我提以往 2020-11-28 02:56

Some iOS photo-related apps store images created with the app somewhere other than the photo library. For example Fat Booth shows a scrolling list of photos created with the

3条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 03:41

    For Swift:

    let imageData = UIImagePNGRepresentation(selectedImage)
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let imagePath = paths.stringByAppendingPathComponent("cached.png")
    
    if !imageData.writeToFile(imagePath, atomically: false)
    {
       println("not saved")
    } else {
       println("saved")
       NSUserDefaults.standardUserDefaults().setObject(imagePath, forKey: "imagePath")
    }
    

    For Swift 2.1:

    let imageData = UIImagePNGRepresentation(selectedImage)
    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    let imageURL = documentsURL.URLByAppendingPathComponent("cached.png")
    
    if !imageData.writeToURL(imageURL, atomically: false)
    {
        print("not saved")
    } else {
        print("saved")
        NSUserDefaults.standardUserDefaults().setObject(imageData, forKey: "imagePath")
    }
    

    stringByAppendingPathComponent is unavailable in Swift 2.1 so you can use URLByAppendingPathComponent. Get more info here.

提交回复
热议问题