2015-11-13 4 views
0

У меня есть UIImage (получен из параметра Parse - convert variable PFFile). Как сохранить и загрузить изображение из этой переменной?Как сохранить и загрузить изображение файла с помощью swift

let a = object["image"] as! PFFile 
    a.getDataInBackgroundWithBlock({ (data:NSData?, error:NSError?) -> Void in 
     if (error == nil) { 
      // I have image, but the next I don't know what I do 
      let image = UIImage(data:data!) 
     } 
    }) 

ответ

1

Сохранить изображение PNG

func saveImage(image:UIImage,name:String){   
    let selectedImage: UIImage = image 
    let data:NSData = UIImagePNGRepresentation(selectedImage) 
    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String 

    let success = fileManager.createFileAtPath(path, contents: data, attributes: nil) 
    print(success) 
    // Check image saved successfully 
    let getImagePath = (path as NSString).stringByAppendingPathComponent(name) 
    if fileManager.fileExistsAtPath(getImagePath) { 
     // image save success 
     let image = UIImage(contentsOfFile: getImagePath)! 
    } 
    else{ 
     // image save error 
    } 
} 

Сохранить другой файл

static func saveFile(fileData:NSData,name:String)->Bool{ 
    let success = NSFileManager.defaultManager().createFileAtPath(path+"/"+name, contents: fileData, attributes: nil) 
    return success 
} 
Смежные вопросы