I have Image cache mechanism in my app. I also need to show local notifications with images. I have a problem. When I try to set UNNotificationAttachment with an image, I get an image from my cache or, if an image doesn't exist, I download it and cache. Then I build a URL to Caches directory, but when I pass this URL to UNNotificationAttachment, I get an error: NSLocalizedDescription=Invalid attachment file URL. What do I make wrong?
if let diskUrlString = UIImageView.sharedImageCache.diskUrlForImageUrl(imageUrl) {
if let diskUrl = URL(string: diskUrlString) {
do {
res = try UNNotificationAttachment(identifier: imageUrlString, url: diskUrl, options: nil)
} catch (let error) {
print("error", error)
// Invalid attachment file URL
}
}
}
func diskUrlForImageUrl(_ imageUrl: URL) -> String? {
let urlRequest = URLRequest(url: imageUrl)
return ImageCache.cacheDirectory.appending("/\(ImageCache.imageCacheKeyFromURLRequest(urlRequest))")
}
static fileprivate var cacheDirectory: String = { () -> String in
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
let res = documentsDirectory.appending("/scAvatars")
let isExist = FileManager.default.fileExists(atPath: res, isDirectory: nil)
if !isExist {
try? FileManager.default.createDirectory(atPath: res, withIntermediateDirectories: true, attributes: nil)
}
return res
}()
I have found that if I add a prefix file:///private to diskUrlString, then URL builds like expected. But I didn't still understand, how to build the url without hardcoding this prefix. So now I can use both cache and UNNotificationAttachment!
The problem here is that you are using a path, not a URL. A path is a string, like "/var/log/foo.log". A URL is semantically more complex than a path. You need a URL that describes the location of the image file on the device file system.
Build a properly constructed URL to the image file and the attachment may work. The attachment may also need a type identifier hint to tell iOS what kind of data is in the file.
You do not have to use urls. You can use image data with UNNotificationAttachment.
Here is a sample code.
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
let imageURL = URL(fileURLWithPath: paths.first!).appendingPathComponent("\(fileName).jpg")
let image = UIImage(contentsOfFile: imageURL.path)
let imageData = image?.pngData()
if let unwrappedImageData = imageData, let attachement = try? UNNotificationAttachment(data: unwrappedImageData, options: nil) {
content.attachments = [attachement]
}
Related
I'm using Realm and storing the file path to captured images as Strings. I want to retrieve them later for use in a tableView. Here's my code to store the path for each image:
func saveImage(imageName: String){
//create an instance of the FileManager
let fileManager = FileManager.default
//get the image path
thisImagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(imageName)
//get the image taken with camera
let image = originalCapturedImage
//get the PNG data for this image
let data = UIImagePNGRepresentation(image!)
//store it in the document directory
fileManager.createFile(atPath: thisImagePath as String, contents: data, attributes: nil)
print("Picture path at assignment \n")
print(thisImagePath as Any)
}
And here's the code to retrieve the image:
...
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsPath = paths[0] //Get the docs directory
let filePath = URL(fileURLWithPath: documentsPath).appendingPathComponent(item.picPath).path
let image = UIImage(contentsOfFile: filePath)
print("Picture path at retrieval \n")
print(item.picPath as Any)
cell.imageWell.image = image
cell.imageWell.clipsToBounds = true
return cell
}
Here's the comparison of the file path at runtime:
Picture path at assignment
/var/mobile/Containers/Data/Application/0E9CACAD-C6B3-4F6C-B0DB-72C43AC722E1/Documents/1535219147
...
...
Picture path at retrieval
/var/mobile/Containers/Data/Application/0E9CACAD-C6B3-4F6C-B0DB-72C43AC722E1/Documents/1535219147
The paths appear identical to me, yet no image appears. I've searched all over SO, and at one point came across a mention of the use of the URL for the file path. Somehow, I lost track of that entry and haven't been able to find it again.
Any help would be greatly appreciated!
You can try with below code for writing the image to the file instead of creating file with content. try? data.write(to: URL(fileURLWithPath: documentsPath))
You can also refer below code for saving image.
class func saveImageToFileWithDirectory(_ imageData:Data, fileName:String, folderName : String? = nil) {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentsDirectory = paths.object(at: 0) as! NSString
let path = documentsDirectory.appendingPathComponent(folderName) as NSString
if !FileManager.default.fileExists(atPath: path as String) {
do {
try FileManager.default.createDirectory(atPath: path as String, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
}
let imagePath = path.appendingPathComponent(fileName)
if !FileManager.default.fileExists(atPath: imagePath as String) {
try? imageData.write(to: URL(fileURLWithPath: imagePath))
} }
Code for retrieving the image looks good. If you need help in that also, pls comment, I will post that also.
Hope this solves your issue.
I am getting a photo's URL using requestContentEditingInput using the PHLibrary
asset.requestContentEditingInput(with: PHContentEditingInputRequestOptions()) { (input, _) in
let url = input?.fullSizeImageURL
}
This URL prints: file:///Users/josh/Library/Developer/CoreSimulator/Devices/EE65D986-55E7-414C-A73E-D1C96FF17004/data/Media/DCIM/100APPLE/IMG_0005.JPG.
How do I retrieve this image? I've tried the following but it does not return anything:
var fileLocation = "file:///Users/josh/Library/Developer/CoreSimulator/Devices/EE65D986-55E7-414C-A73E-D1C96FF17004/data/Media/DCIM/100APPLE/IMG_0005.JPG"
let url = URL(string: fileLocation)
let asset = PHAsset.fetchAssets(withALAssetURLs: [url!], options: nil)
if let result = asset.firstObject {
//asset.firstObject does not exist
}
apparently apple will not allow the developer to access any and every photo in the user's photo library even after they have accepted photos usage. If you are using an image that hasnt been picked from the imagePicker, (i.e. choosing last image in library), you have to store the image in the document directory before you can use the document directory URL. I guess this prevents people hacking into others photo library
//Storing the image (in my case, when selecting last photo NOT via imagePicker)
let fileManager = FileManager.default
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("image01.jpg")
let imageData = UIImageJPEGRepresentation(image!, 1.0)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
//Retrieving the image
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("image01.jpg")
if let imageRetrieved = UIImage(contentsOfFile: imageURL.path) {
//do whatever you want with this image
print(imageRetrieved)
}
}
I am trying to upload a video to a server file through Alamofire but I couldn't get the "data" going to be passed..its always nil
var videoURL = NSURL(string: "")
//returns Optional(file:///private/var/mobile/Containers/Data/Application/1FB40086-228B-4011-A9D4-7874E2EEF9F4/tmp/4A6AAD76-B899-4B67-8E96-925DA4AE9E93.mov)
let videodata = NSData(contentsOfFile: (videoURL?.absoluteString)!)
//nil
let url = NSURL(fileURLWithPath: (videoURL?.absoluteString)!)
let videodata = NSData(contentsOf: url as URL)
//nil
If I get data would lead a way for me to do this:
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append (videodata as! Data, withName: "file", fileName: "file.mov", mimeType: "video/quicktime")
enter code here
EDIT::
thank you guys, with your help I have struggled my way out of there to this file not found error, but I can see the file is being saved in my gallery, any clue would save my day.
print (videoURL!)
//returns file:///private/var/mobile/Containers/Data/Application/3F280477-DA16-4A67-AE60-D6247143352E/tmp/1E4AC002-6AD0-41E1-9E0D-A09B697F81F7.mov
print (videoURL!.path!)
// returns /private/var/mobile/Containers/Data/Application/3F280477-DA16-4A67-AE60-D6247143352E/tmp/1E4AC002-6AD0-41E1-9E0D-A09B697F81F7.mov
var videoData = NSData()
let path = videoURL!.path!
if FileManager.default.fileExists(atPath: path) {
}else {
print("Could not fin file at url: \(videoURL!.path!)")
// here it throws file not found
}
In Swift 3 use native URL and Data instead of NSURL and NSData.
if let videoURL = URL(string: urlString), let videodata = try? Data(contentsOf: videoURL) {
//Add code of Alamofire here
}
Using absoluteString returns a string that includes file:// at the beginning and you don't want that. You need to return the path of the URL
guard let videoPathString = videoURL.path as? String else {
//handle error here if you can't create a path string
return
}
var videoData = NSData()
//check if file exists at this path first
if (NSFileManager.defaultManager().fileExistsAtPath(videoPathString)) {
videoData = NSData(contentsOfFile: NSString(videoPathString))
} else {
//if file does not exist at that path, handle here
}
Using this code, I extract an image from a Share Extension and I write it to a directory I created in an App Group.
let content = self.extensionContext!.inputItems[0] as! NSExtensionItem
let contentType = kUTTypeImage as String
for attachment in content.attachments as! [NSItemProvider] {
if attachment.hasItemConformingToTypeIdentifier(contentType) {
attachment.loadItem(forTypeIdentifier: contentType, options: nil) { data, error in
// from here
if error == nil {
let url = data as! NSURL
let originalFileName = url.lastPathComponent
if let imageData = NSData(contentsOf: url as URL) {
let img = UIImage(data:imageData as Data)
if let data = UIImagePNGRepresentation(img!) {
// write, etc.
}
}
}
}
Anything is working fine.
What I'd like to know is if it is possible to reduce some code: in particular, after if error == nil, I:
cast data to NSURL;
use NSURL to get a NSData;
use NSData to get a UIImage;
use UIImage to get a UIImagePNGRepresentation;
Aside from avoiding the creation of the imageData variable, isn't there a way to (safely) achieve the same goal with fewer steps?
First of all you need to use native Data and URL instead of NSData & NSURL also if you want to write file in DocumentDirectory then you can directly use that imageData no need to make UIImage object from it and then convert it to data using UIImagePNGRepresentation.
if let url = data as? URL, error == nil {
let originalFileName = url.lastPathComponent
if let imageData = try? Data(contentsOf: data) {
// write, etc.
var destinationURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
destinationURL.appendPathComponent("fileName.png")
try? imageData.write(to: destinationURL)
}
}
I am using NSUrlconnection to call to api but now i have also receive image from api so i don't know how to load the image & save into phones local memory because these images are further using in app . please help me. how to use & show image from local save.I am using below function to load the image but NSURLSession.sharedSession() are not going to inside the queue.
func saveImage(url:NSString,image_name1:NSString)
{
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url as String)!, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error)
return
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let image = UIImage(data: data!)
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
let path = NSURL(fileURLWithPath: documentsDirectory).URLByAppendingPathComponent(image_name1 as String)!.absoluteString
print(" file path is \(path)")
let data = UIImagePNGRepresentation(image!)
data!.writeToFile(path!, atomically: true)
})
}).resume()
}
for save
var image = .... // However you create/get a UIImage
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let destinationPath = documentsPath.stringByAppendingPathComponent("filename.jpg")
UIImageJPEGRepresentation(image,1.0).writeToFile(destinationPath, atomically: true)
for cash
https://github.com/onevcat/Kingfisher
pod 'Kingfisher'
let url = URL(string: "url_of_your_image")
imageView.kf.setImage(with: url)
it's automatic cash images
Try this :
let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
imageView.image = UIImage(data: data!)
From : https://stackoverflow.com/a/27517280/3901620