Swift 3 将图像添加到文档并检索
Swift 3 adding an Image to Documents and Retrieving
我觉得我错过了一些重要的东西,因为我没有收到任何错误或空值,但是每当我尝试检索我的图像时,它 returns ""
因为它不存在?
这是我传递图像数据的方式:
URLSession.shared.dataTask(with: url! as URL, completionHandler:{ (data, response, error) in
//if download error
if error != nil{
print(error!)
return
}
guard let imageData = UIImage(data: data!) else { return }
DispatchQueue.main.async{
self.imgPortrait.image = imageData
ImagePortrait().saveImageDocumentDirectory(image: imageData)
}
数据显示在 imgPortrait
上完全没问题。以下是其余函数,其中: /\(userUID)/\(CharacterSelection.sharedInstance.getActiveCharacterName())
是可选的。当它检索图像和保存图像时,我可以确认路径完全相同。我觉得这就是我用 createFile
保存图像的方式,但我不确定。
func saveImageDocumentDirectory(image: UIImage){
if let userUID = Auth.auth().currentUser?.uid{
let fileManager = FileManager.default
let paths = (getDirectoryPath() as NSString).appendingPathComponent("/\(userUID)/\(CharacterSelection.sharedInstance.getActiveCharacterName())/characterPortrait.png")
createDirectory(name: (getDirectoryPath() as NSString) as String)
let imageData = UIImagePNGRepresentation(image)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
}
}
func getDirectoryPath() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
return documentsDirectory
}
func getImage() -> String{
if let userUID = Auth.auth().currentUser?.uid{
let fileManager = FileManager.default
let imagePath = (self.getDirectoryPath() as NSString).appendingPathComponent("/\(userUID)/\(CharacterSelection.sharedInstance.getActiveCharacterName())/characterPortrait.png")
if fileManager.fileExists(atPath: imagePath){
return imagePath
}else{
print("No Image")
return ""
}
}
else{
return ""
}
}
func createDirectory(name: String){
let fileManager = FileManager.default
let paths = (getDirectoryPath() as NSString).appendingPathComponent(name)
if !fileManager.fileExists(atPath: paths){
try! fileManager.createDirectory(atPath: paths, withIntermediateDirectories: true, attributes: nil)
}else{
print("Directory is already created.")
}
}
提前致谢!
好吧,几个小时后我弄明白了。看起来目录没有被创建。解决方法:
func saveImageDocumentDirectory(image: UIImage){
if let userUID = Auth.auth().currentUser?.uid{
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("\(userUID)_\(CharacterSelection.sharedInstance.getActiveCharacterName())_characterPortrait.png")
do {
try UIImagePNGRepresentation(image)?.write(to: fileURL, options: .atomic)
} catch {
print(error)
}
}
}
func getImage() -> UIImage{
if let userUID = Auth.auth().currentUser?.uid{
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("\(userUID)_\(CharacterSelection.sharedInstance.getActiveCharacterName())_characterPortrait.png")
if let image = UIImage(contentsOfFile: imageURL.path){
return image
}
else{
print("Image isn't found.")
return UIImage(named: "default_portrait.png")!
}
}
else{
print("Image isn't found.")
return UIImage(named: "default_portrait.png")!
}
}
else{
print("Image isn't found.")
return UIImage(named: "default_portrait.png")!
}
}
我觉得我错过了一些重要的东西,因为我没有收到任何错误或空值,但是每当我尝试检索我的图像时,它 returns ""
因为它不存在?
这是我传递图像数据的方式:
URLSession.shared.dataTask(with: url! as URL, completionHandler:{ (data, response, error) in
//if download error
if error != nil{
print(error!)
return
}
guard let imageData = UIImage(data: data!) else { return }
DispatchQueue.main.async{
self.imgPortrait.image = imageData
ImagePortrait().saveImageDocumentDirectory(image: imageData)
}
数据显示在 imgPortrait
上完全没问题。以下是其余函数,其中: /\(userUID)/\(CharacterSelection.sharedInstance.getActiveCharacterName())
是可选的。当它检索图像和保存图像时,我可以确认路径完全相同。我觉得这就是我用 createFile
保存图像的方式,但我不确定。
func saveImageDocumentDirectory(image: UIImage){
if let userUID = Auth.auth().currentUser?.uid{
let fileManager = FileManager.default
let paths = (getDirectoryPath() as NSString).appendingPathComponent("/\(userUID)/\(CharacterSelection.sharedInstance.getActiveCharacterName())/characterPortrait.png")
createDirectory(name: (getDirectoryPath() as NSString) as String)
let imageData = UIImagePNGRepresentation(image)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
}
}
func getDirectoryPath() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
return documentsDirectory
}
func getImage() -> String{
if let userUID = Auth.auth().currentUser?.uid{
let fileManager = FileManager.default
let imagePath = (self.getDirectoryPath() as NSString).appendingPathComponent("/\(userUID)/\(CharacterSelection.sharedInstance.getActiveCharacterName())/characterPortrait.png")
if fileManager.fileExists(atPath: imagePath){
return imagePath
}else{
print("No Image")
return ""
}
}
else{
return ""
}
}
func createDirectory(name: String){
let fileManager = FileManager.default
let paths = (getDirectoryPath() as NSString).appendingPathComponent(name)
if !fileManager.fileExists(atPath: paths){
try! fileManager.createDirectory(atPath: paths, withIntermediateDirectories: true, attributes: nil)
}else{
print("Directory is already created.")
}
}
提前致谢!
好吧,几个小时后我弄明白了。看起来目录没有被创建。解决方法:
func saveImageDocumentDirectory(image: UIImage){
if let userUID = Auth.auth().currentUser?.uid{
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("\(userUID)_\(CharacterSelection.sharedInstance.getActiveCharacterName())_characterPortrait.png")
do {
try UIImagePNGRepresentation(image)?.write(to: fileURL, options: .atomic)
} catch {
print(error)
}
}
}
func getImage() -> UIImage{
if let userUID = Auth.auth().currentUser?.uid{
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("\(userUID)_\(CharacterSelection.sharedInstance.getActiveCharacterName())_characterPortrait.png")
if let image = UIImage(contentsOfFile: imageURL.path){
return image
}
else{
print("Image isn't found.")
return UIImage(named: "default_portrait.png")!
}
}
else{
print("Image isn't found.")
return UIImage(named: "default_portrait.png")!
}
}
else{
print("Image isn't found.")
return UIImage(named: "default_portrait.png")!
}
}