read a temp folder file in swift 3 [duplicate] - swift

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.

Related

url to pdf return nil value [duplicate]

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.

File at URL is not reachable. Uploading video to firebase storage - Swift [duplicate]

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.

get real file path with swift with whitespace [duplicate]

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.

Read image from Library/Caches/temporary/ [duplicate]

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.

OSX - Loading an image and saving it as a smaller png file using Swift

I am looking for a way to to upload an image file, resize it (in order to reduce the total file size), and then save it as a png. I think there must be a fairly straightforward way of doing this, but hours of searching around have yielded no effective results. I have been able to achieve the desired file size by exporting the image as a compressed JPEG, but I need to preserve transparency. Here is the code I used to get the JPEG:
func chooseImage () {
var image = NSImage()
//choose image from hard disk
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.runModal()
panel.allowedFileTypes = ["png", "jpeg", "jpg"]
let chosenFile = panel.URL
//convert to NSData and send to Jpeg function
if chosenFile != nil {
image = NSImage(contentsOfURL: chosenFile!)!
let imageData = image.TIFFRepresentation
self.saveAsJpeg(imageData!, compression: 0.5)
}
}
func saveAsJpeg (image:NSData, compression:NSNumber) {
// make imagerep and define properties
let imgRep = NSBitmapImageRep(data: image)
let props = NSDictionary.init(object: compression, forKey: NSImageCompressionFactor)
let pingy = imgRep?.representationUsingType(NSBitmapImageFileType.NSJPEGFileType, properties: props as! [String : AnyObject])
//save to disk
let documentURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let folderURL = documentURL.URLByAppendingPathComponent("KKNightlife Data")
let g = GetUniqueID()
let fileName = g.getUniqueID() + ".jpeg"
do {
try NSFileManager.defaultManager().createDirectoryAtURL(folderURL, withIntermediateDirectories: false, attributes: nil)
} catch {
print("cannot create directory - folder Exists?")
}
let url = folderURL.URLByAppendingPathComponent(fileName)
if let pid = pingy {
pid.writeToURL(url, atomically: false)
} else {
print("error saving image")
}
}
I attempted to use the following code to scale the image in order to create a smaller .png file, but no matter what values I enter for the size, the resulting file is the same size (both in terms of height/width and overall file size):
func chooseImage (size:String) {
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.runModal()
panel.allowedFileTypes = ["png", "jpeg", "jpg"]
let chosenFile = panel.URL
if chosenFile != nil {
let image = NSImage(contentsOfURL: chosenFile!)
self.scaleImage(image!)
}
}
func scaleImage (image:NSImage) {
//create resized image
let newSize = NSSize(width: 10, height: 10)
var imageRect:CGRect = CGRectMake(0, 0, image.size.width, image.size.height)
let imageRef = image.CGImageForProposedRect(&imageRect, context: nil, hints: nil)
let resizedImage = NSImage(CGImage: imageRef!, size: newSize)
let imageData = resizedImage.TIFFRepresentation
//make imagerep
let imgRep = NSBitmapImageRep(data: imageData!)
let pingy = imgRep?.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [:])
//save to disk
let documentURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let g = GetUniqueID()
let fileName = g.getUniqueID() + ".png"
let folderURL = documentURL.URLByAppendingPathComponent("KKNightlife Data")
do {
try NSFileManager.defaultManager().createDirectoryAtURL(folderURL, withIntermediateDirectories: false, attributes: nil)
} catch {
print("cannot create directory - folder Exists?")
}
let url = folderURL.URLByAppendingPathComponent(fileName)
if let pid = pingy {
pid.writeToURL(url, atomically: false)
print("image is at \(documentURL)")
} else {
print("error saving image")
}
}
Any suggestions would be greatly appreciated.
I was finally able to do this using the extensions found here:
https://gist.github.com/raphaelhanneken/cb924aa280f4b9dbb480
This is how I ended up calling them in case anyone encounters similar problems:
func chooseImage (size:String) {
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.runModal()
panel.allowedFileTypes = ["png", "jpeg", "jpg"]
let chosenFile = panel.URL
if chosenFile != nil {
let image = NSImage(contentsOfURL: chosenFile!)
self.scaleImageUsingExtensions(image!)
}
}
func scaleImageUsingExtensions (image:NSImage){
let size: NSSize = NSMakeSize(10, 10)
let resizedImage = image.resizeWhileMaintainingAspectRatioToSize(size)
let documentURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let g = GetUniqueID()
let fileName = g.getUniqueID() + ".png"
let folderURL = documentURL.URLByAppendingPathComponent("KKNightlife Data")
do {
try NSFileManager.defaultManager().createDirectoryAtURL(folderURL, withIntermediateDirectories: false, attributes: nil)
} catch {
print("cannot create directory - folder Exists?")
}
let url = folderURL.URLByAppendingPathComponent(fileName)
do {
try resizedImage?.savePNGRepresentationToURL(url)
}
catch {
print("error saving file")
}
}