So I am using the methods bellow to handle getting, deleting, and saving images for my app. When I call removeImage it succeeds and when I use NSFileManager.defaultManager().fileExistsAtPath it says the file does not exist. However, when I call getImage it can still grab the image even though it has been deleted. When I quite the app and start it up again getImage works as expected until I use removeImage. I have also tried wrapping the removeImage call in dispatch_async(dispatch_get_main_queue(),{}) and it still doesn't work.
My code:
class func removeImage(user:User){
let context = getManagedObjectContext()
context.performBlockAndWait({
guard let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as [String]! where paths.count > 0 else{
return
}
do{
if let dirPath = paths[0] as String!{
let path = "\(user.id)_\(user.name).png"
let readPath = (dirPath as NSString).stringByAppendingPathComponent(path)
try NSFileManager.defaultManager().removeItemAtPath(readPath)
}
}catch{
}
})
}
class func saveImage(user:User,image:UIImage){
let path = "\(user.id)_\(user.name).png"
guard let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as [String]! where paths.count > 0 else{
return
}
if let dirPath = paths[0] as String!{
let writePath = (dirPath as NSString).stringByAppendingPathComponent(path)
UIImagePNGRepresentation(image)!.writeToFile(writePath, atomically: true)
}
}
class func getImage(user:User)->UIImage?{
let path = "\(user.id)_\(user.name).png"
guard let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as [String]! where paths.count > 0 else{
return nil
}
if let dirPath = paths[0] as String!{
let readPath = (dirPath as NSString).stringByAppendingPathComponent(path)
return UIImage(named: readPath)
}
return nil
}
UPDATE/FIX! Changed code to this and it worked:
class func removeImage(user:User){
let manager = NSFileManager.defaultManager()
do{
let directoryURL = try manager.URLForDirectory(.DocumentationDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
if #available(iOS 9.0, *) {
let url = NSURL(fileURLWithPath: "\(user.id)_\(user.name).png", relativeToURL: directoryURL)
try manager.removeItemAtURL(url)
} else {
let url = directoryURL.URLByAppendingPathComponent("\(user.id)_\(user.name).png")
try manager.removeItemAtURL(url)
}
}catch{
}
}
class func saveImage(user:User,image:UIImage){
let manager = NSFileManager.defaultManager()
do{
let directoryURL = try manager.URLForDirectory(.DocumentationDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
if #available(iOS 9.0, *) {
let url = NSURL(fileURLWithPath: "\(user.id)_\(user.name).png", relativeToURL: directoryURL)
UIImagePNGRepresentation(image)!.writeToURL(url, atomically: true)
} else {
let url = directoryURL.URLByAppendingPathComponent("\(user.id)_\(user.name).png")
UIImagePNGRepresentation(image)!.writeToURL(url, atomically: true)
}
}catch{
}
}
class func getImage(user:User)->UIImage?{
let manager = NSFileManager.defaultManager()
do{
let directoryURL = try manager.URLForDirectory(.DocumentationDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
if #available(iOS 9.0, *) {
let url = NSURL(fileURLWithPath: "\(user.id)_\(user.name).png", relativeToURL: directoryURL)
if let data = NSData(contentsOfURL: url){
return UIImage(data: data)
}
} else {
let url = directoryURL.URLByAppendingPathComponent("\(user.id)_\(user.name).png")
if let data = NSData(contentsOfURL: url){
return UIImage(data: data)
}
}
}catch{
}
return nil
}
Related
This question already has answers here:
NSFileManager.defaultManager().fileExistsAtPath returns false instead of true
(2 answers)
Closed 4 years ago.
I'm trying to save a snapshot of a map with an overlay in the caches directory and retrieve it when it exists. However, despite the file being created, UIImage(contentsOfFile:) returns nil when I try to retrieve it. I've printed the file paths for both write and read and they are the same and have verified the file exists by downloading the container and checking the directory and the file definitely exists.
Any idea what the problem here is?
let cachesDirectory: URL = {
let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
return urls[urls.endIndex - 1]
}()
let mapCachesDirectory = cachesDirectory.appendingPathComponent("map-snapshots", isDirectory: true)
func configureMap(data: NSSet?) {
mapView.isZoomEnabled = false
mapView.isScrollEnabled = false
mapView.isUserInteractionEnabled = false
guard let data = data as? Set<SessionData>, data.count > 0 else { return }
activityIndicatorView.isHidden = false
activityIndicatorView.startAnimating()
DispatchQueue.global(qos: .userInitiated).async {
var points = [CLLocationCoordinate2D]()
for object in data {
guard object.locationLatitude != 0, object.locationLatitude != 0 else { continue }
points.append(CLLocationCoordinate2DMake(object.locationLatitude, object.locationLongitude))
}
DispatchQueue.main.async(execute: {
self.createOverlay(points: points)
self.activityIndicatorView.stopAnimating()
self.activityIndicatorView.isHidden = true
self.cacheMapImage(view: self.mapView)
})
}
}
func cacheMapImage(view: UIView) {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let compositeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
DispatchQueue.global(qos: .userInitiated).async {
if let compositeImage = compositeImage, let info = self.info {
let data = UIImagePNGRepresentation(compositeImage)
do {
var isDirectory: ObjCBool = false
let fileManager = FileManager.default
if fileManager.fileExists(atPath: self.mapCachesDirectory.absoluteString, isDirectory: &isDirectory) == false {
try fileManager.createDirectory(at: self.mapCachesDirectory, withIntermediateDirectories: true, attributes: nil)
}
let fileURL = self.mapCachesDirectory.appendingPathComponent(info.uid).appendingPathExtension("png")
try data?.write(to: fileURL)
print("\(fileURL.absoluteString) Saved")
} catch {
log.error(error)
}
}
}
}
func cachedMapImage() -> UIImage? {
guard let info = info else { return nil }
let filePath = mapCachesDirectory.appendingPathComponent(info.uid).appendingPathExtension("png").absoluteString
let image = UIImage(contentsOfFile: filePath)
print("\(filePath): \(image)")
return image
}
func createOverlay(points: [CLLocationCoordinate2D]) {
guard points.count > 0 else { return }
let overlay = MKGeodesicPolyline(coordinates: points, count: points.count)
mapView.add(overlay)
let inset: CGFloat = 50.0
mapView.setVisibleMapRect(overlay.boundingMapRect, edgePadding: UIEdgeInsetsMake(inset,inset,inset,inset), animated: true)
}
The problem there is that you are using URL property absoluteString where you should be using the path property. The difference between absoluteString and path properties is that absoluteString includes the file url scheme ("file://") which is the reason it doesn't find the file at what was supposed to be its path but it is actually its absoluteString.
This question already has answers here:
NSFileManager.defaultManager().fileExistsAtPath returns false instead of true
(2 answers)
Closed 4 years ago.
I'm trying to save a snapshot of a map with an overlay in the caches directory and retrieve it when it exists. However, despite the file being created, UIImage(contentsOfFile:) returns nil when I try to retrieve it. I've printed the file paths for both write and read and they are the same and have verified the file exists by downloading the container and checking the directory and the file definitely exists.
Any idea what the problem here is?
let cachesDirectory: URL = {
let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
return urls[urls.endIndex - 1]
}()
let mapCachesDirectory = cachesDirectory.appendingPathComponent("map-snapshots", isDirectory: true)
func configureMap(data: NSSet?) {
mapView.isZoomEnabled = false
mapView.isScrollEnabled = false
mapView.isUserInteractionEnabled = false
guard let data = data as? Set<SessionData>, data.count > 0 else { return }
activityIndicatorView.isHidden = false
activityIndicatorView.startAnimating()
DispatchQueue.global(qos: .userInitiated).async {
var points = [CLLocationCoordinate2D]()
for object in data {
guard object.locationLatitude != 0, object.locationLatitude != 0 else { continue }
points.append(CLLocationCoordinate2DMake(object.locationLatitude, object.locationLongitude))
}
DispatchQueue.main.async(execute: {
self.createOverlay(points: points)
self.activityIndicatorView.stopAnimating()
self.activityIndicatorView.isHidden = true
self.cacheMapImage(view: self.mapView)
})
}
}
func cacheMapImage(view: UIView) {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let compositeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
DispatchQueue.global(qos: .userInitiated).async {
if let compositeImage = compositeImage, let info = self.info {
let data = UIImagePNGRepresentation(compositeImage)
do {
var isDirectory: ObjCBool = false
let fileManager = FileManager.default
if fileManager.fileExists(atPath: self.mapCachesDirectory.absoluteString, isDirectory: &isDirectory) == false {
try fileManager.createDirectory(at: self.mapCachesDirectory, withIntermediateDirectories: true, attributes: nil)
}
let fileURL = self.mapCachesDirectory.appendingPathComponent(info.uid).appendingPathExtension("png")
try data?.write(to: fileURL)
print("\(fileURL.absoluteString) Saved")
} catch {
log.error(error)
}
}
}
}
func cachedMapImage() -> UIImage? {
guard let info = info else { return nil }
let filePath = mapCachesDirectory.appendingPathComponent(info.uid).appendingPathExtension("png").absoluteString
let image = UIImage(contentsOfFile: filePath)
print("\(filePath): \(image)")
return image
}
func createOverlay(points: [CLLocationCoordinate2D]) {
guard points.count > 0 else { return }
let overlay = MKGeodesicPolyline(coordinates: points, count: points.count)
mapView.add(overlay)
let inset: CGFloat = 50.0
mapView.setVisibleMapRect(overlay.boundingMapRect, edgePadding: UIEdgeInsetsMake(inset,inset,inset,inset), animated: true)
}
The problem there is that you are using URL property absoluteString where you should be using the path property. The difference between absoluteString and path properties is that absoluteString includes the file url scheme ("file://") which is the reason it doesn't find the file at what was supposed to be its path but it is actually its absoluteString.
This question already has answers here:
NSFileManager.defaultManager().fileExistsAtPath returns false instead of true
(2 answers)
Closed 4 years ago.
I'm trying to save a snapshot of a map with an overlay in the caches directory and retrieve it when it exists. However, despite the file being created, UIImage(contentsOfFile:) returns nil when I try to retrieve it. I've printed the file paths for both write and read and they are the same and have verified the file exists by downloading the container and checking the directory and the file definitely exists.
Any idea what the problem here is?
let cachesDirectory: URL = {
let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
return urls[urls.endIndex - 1]
}()
let mapCachesDirectory = cachesDirectory.appendingPathComponent("map-snapshots", isDirectory: true)
func configureMap(data: NSSet?) {
mapView.isZoomEnabled = false
mapView.isScrollEnabled = false
mapView.isUserInteractionEnabled = false
guard let data = data as? Set<SessionData>, data.count > 0 else { return }
activityIndicatorView.isHidden = false
activityIndicatorView.startAnimating()
DispatchQueue.global(qos: .userInitiated).async {
var points = [CLLocationCoordinate2D]()
for object in data {
guard object.locationLatitude != 0, object.locationLatitude != 0 else { continue }
points.append(CLLocationCoordinate2DMake(object.locationLatitude, object.locationLongitude))
}
DispatchQueue.main.async(execute: {
self.createOverlay(points: points)
self.activityIndicatorView.stopAnimating()
self.activityIndicatorView.isHidden = true
self.cacheMapImage(view: self.mapView)
})
}
}
func cacheMapImage(view: UIView) {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let compositeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
DispatchQueue.global(qos: .userInitiated).async {
if let compositeImage = compositeImage, let info = self.info {
let data = UIImagePNGRepresentation(compositeImage)
do {
var isDirectory: ObjCBool = false
let fileManager = FileManager.default
if fileManager.fileExists(atPath: self.mapCachesDirectory.absoluteString, isDirectory: &isDirectory) == false {
try fileManager.createDirectory(at: self.mapCachesDirectory, withIntermediateDirectories: true, attributes: nil)
}
let fileURL = self.mapCachesDirectory.appendingPathComponent(info.uid).appendingPathExtension("png")
try data?.write(to: fileURL)
print("\(fileURL.absoluteString) Saved")
} catch {
log.error(error)
}
}
}
}
func cachedMapImage() -> UIImage? {
guard let info = info else { return nil }
let filePath = mapCachesDirectory.appendingPathComponent(info.uid).appendingPathExtension("png").absoluteString
let image = UIImage(contentsOfFile: filePath)
print("\(filePath): \(image)")
return image
}
func createOverlay(points: [CLLocationCoordinate2D]) {
guard points.count > 0 else { return }
let overlay = MKGeodesicPolyline(coordinates: points, count: points.count)
mapView.add(overlay)
let inset: CGFloat = 50.0
mapView.setVisibleMapRect(overlay.boundingMapRect, edgePadding: UIEdgeInsetsMake(inset,inset,inset,inset), animated: true)
}
The problem there is that you are using URL property absoluteString where you should be using the path property. The difference between absoluteString and path properties is that absoluteString includes the file url scheme ("file://") which is the reason it doesn't find the file at what was supposed to be its path but it is actually its absoluteString.
This question already has answers here:
NSFileManager.defaultManager().fileExistsAtPath returns false instead of true
(2 answers)
Closed 5 years ago.
I'm trying to save a snapshot of a map with an overlay in the caches directory and retrieve it when it exists. However, despite the file being created, UIImage(contentsOfFile:) returns nil when I try to retrieve it. I've printed the file paths for both write and read and they are the same and have verified the file exists by downloading the container and checking the directory and the file definitely exists.
Any idea what the problem here is?
let cachesDirectory: URL = {
let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
return urls[urls.endIndex - 1]
}()
let mapCachesDirectory = cachesDirectory.appendingPathComponent("map-snapshots", isDirectory: true)
func configureMap(data: NSSet?) {
mapView.isZoomEnabled = false
mapView.isScrollEnabled = false
mapView.isUserInteractionEnabled = false
guard let data = data as? Set<SessionData>, data.count > 0 else { return }
activityIndicatorView.isHidden = false
activityIndicatorView.startAnimating()
DispatchQueue.global(qos: .userInitiated).async {
var points = [CLLocationCoordinate2D]()
for object in data {
guard object.locationLatitude != 0, object.locationLatitude != 0 else { continue }
points.append(CLLocationCoordinate2DMake(object.locationLatitude, object.locationLongitude))
}
DispatchQueue.main.async(execute: {
self.createOverlay(points: points)
self.activityIndicatorView.stopAnimating()
self.activityIndicatorView.isHidden = true
self.cacheMapImage(view: self.mapView)
})
}
}
func cacheMapImage(view: UIView) {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let compositeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
DispatchQueue.global(qos: .userInitiated).async {
if let compositeImage = compositeImage, let info = self.info {
let data = UIImagePNGRepresentation(compositeImage)
do {
var isDirectory: ObjCBool = false
let fileManager = FileManager.default
if fileManager.fileExists(atPath: self.mapCachesDirectory.absoluteString, isDirectory: &isDirectory) == false {
try fileManager.createDirectory(at: self.mapCachesDirectory, withIntermediateDirectories: true, attributes: nil)
}
let fileURL = self.mapCachesDirectory.appendingPathComponent(info.uid).appendingPathExtension("png")
try data?.write(to: fileURL)
print("\(fileURL.absoluteString) Saved")
} catch {
log.error(error)
}
}
}
}
func cachedMapImage() -> UIImage? {
guard let info = info else { return nil }
let filePath = mapCachesDirectory.appendingPathComponent(info.uid).appendingPathExtension("png").absoluteString
let image = UIImage(contentsOfFile: filePath)
print("\(filePath): \(image)")
return image
}
func createOverlay(points: [CLLocationCoordinate2D]) {
guard points.count > 0 else { return }
let overlay = MKGeodesicPolyline(coordinates: points, count: points.count)
mapView.add(overlay)
let inset: CGFloat = 50.0
mapView.setVisibleMapRect(overlay.boundingMapRect, edgePadding: UIEdgeInsetsMake(inset,inset,inset,inset), animated: true)
}
The problem there is that you are using URL property absoluteString where you should be using the path property. The difference between absoluteString and path properties is that absoluteString includes the file url scheme ("file://") which is the reason it doesn't find the file at what was supposed to be its path but it is actually its absoluteString.
This question already has answers here:
NSFileManager.defaultManager().fileExistsAtPath returns false instead of true
(2 answers)
Closed 5 years ago.
I'm trying to save a snapshot of a map with an overlay in the caches directory and retrieve it when it exists. However, despite the file being created, UIImage(contentsOfFile:) returns nil when I try to retrieve it. I've printed the file paths for both write and read and they are the same and have verified the file exists by downloading the container and checking the directory and the file definitely exists.
Any idea what the problem here is?
let cachesDirectory: URL = {
let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
return urls[urls.endIndex - 1]
}()
let mapCachesDirectory = cachesDirectory.appendingPathComponent("map-snapshots", isDirectory: true)
func configureMap(data: NSSet?) {
mapView.isZoomEnabled = false
mapView.isScrollEnabled = false
mapView.isUserInteractionEnabled = false
guard let data = data as? Set<SessionData>, data.count > 0 else { return }
activityIndicatorView.isHidden = false
activityIndicatorView.startAnimating()
DispatchQueue.global(qos: .userInitiated).async {
var points = [CLLocationCoordinate2D]()
for object in data {
guard object.locationLatitude != 0, object.locationLatitude != 0 else { continue }
points.append(CLLocationCoordinate2DMake(object.locationLatitude, object.locationLongitude))
}
DispatchQueue.main.async(execute: {
self.createOverlay(points: points)
self.activityIndicatorView.stopAnimating()
self.activityIndicatorView.isHidden = true
self.cacheMapImage(view: self.mapView)
})
}
}
func cacheMapImage(view: UIView) {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let compositeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
DispatchQueue.global(qos: .userInitiated).async {
if let compositeImage = compositeImage, let info = self.info {
let data = UIImagePNGRepresentation(compositeImage)
do {
var isDirectory: ObjCBool = false
let fileManager = FileManager.default
if fileManager.fileExists(atPath: self.mapCachesDirectory.absoluteString, isDirectory: &isDirectory) == false {
try fileManager.createDirectory(at: self.mapCachesDirectory, withIntermediateDirectories: true, attributes: nil)
}
let fileURL = self.mapCachesDirectory.appendingPathComponent(info.uid).appendingPathExtension("png")
try data?.write(to: fileURL)
print("\(fileURL.absoluteString) Saved")
} catch {
log.error(error)
}
}
}
}
func cachedMapImage() -> UIImage? {
guard let info = info else { return nil }
let filePath = mapCachesDirectory.appendingPathComponent(info.uid).appendingPathExtension("png").absoluteString
let image = UIImage(contentsOfFile: filePath)
print("\(filePath): \(image)")
return image
}
func createOverlay(points: [CLLocationCoordinate2D]) {
guard points.count > 0 else { return }
let overlay = MKGeodesicPolyline(coordinates: points, count: points.count)
mapView.add(overlay)
let inset: CGFloat = 50.0
mapView.setVisibleMapRect(overlay.boundingMapRect, edgePadding: UIEdgeInsetsMake(inset,inset,inset,inset), animated: true)
}
The problem there is that you are using URL property absoluteString where you should be using the path property. The difference between absoluteString and path properties is that absoluteString includes the file url scheme ("file://") which is the reason it doesn't find the file at what was supposed to be its path but it is actually its absoluteString.