Load image from local URL file with path - ios

In my application, I am writing an image to a URL file and saving the relative URL in order to retrieve the image later on. This is what I am doing, but it is not working. Is there anything you see wrong.
let imageRelativeURL = pendingPostData[2]
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let urlString = "\(documentsPath)/\(imageRelativeURL).jpg"
let image = UIImage(contentsOfFile: urlString)
// This is the line that is causing the error
let imageData = UIImageJPEGRepresentation(image!, 1.0)
I am getting this error:
Thread 1: FATAL ERROR: Unexpectedly found nil while wrapping an Optional Value
This is how I am saving the relative URL.
let uniqueRelativeID = NSUUID().uuidString
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let outputPath = "\(documentsPath)/\(uniqueRelativeID).jpg"
let relativePath = "\(uniqueRelativeID).jpg"
let relativeURL = URL(fileURLWithPath: relativePath)
let imageURL = URL(fileURLWithPath: outputPath, relativeTo: relativeURL)
do {
try UIImageJPEGRepresentation(chosenImg, 1.0)?.write(to: imageURL)
} catch {
print("There was a problem writing image file.")
}
saveVideoData(data: imageURL.relativeString)

Related

how to get the file name from image path

i am trying to get the file name from image pathurl
but i am getting an error like "Cannot convert value of type 'URL' to type 'NSString' in coercion"can anyone help me to convert as NSstring .Thanks in advance
if var imgUrl = info[UIImagePickerController.InfoKey.imageURL] as? URL{
let imgName = imgUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let localPath = documentDirectory?.appending(imgName)
var image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
let data = image.pngData()! as NSData
data.write(toFile: localPath!, atomically: true)
//let imageData = NSData(contentsOfFile: localPath!)!
let photoURL = URL.init(fileURLWithPath: localPath!)//NSURL(fileURLWithPath: localPath!)
print(photoURL)
let filename = (photoURL as NSString).lastPathComponent
// pdfURL is your file url
let fileExtention = (filename as NSString).pathExtension // get your file extension
let pathPrefix = (filename as NSString).deletingPathExtension
img.image = image
(In Swift) all methods for path manipulation are in the URL struct. No conversion needed
let filename = photoURL.lastPathComponent
// pdfURL is your file url
let fileExtention = photoURL.pathExtension // get your file extension
let pathPrefix = photoURL.deletingPathExtension.lastPathComponent
img.image = image
And don't use NS classes in Swift at all if there is a native equivalent.
And please consider warnings like
Variable 'image' was never mutated; consider changing to 'let' constant

wkwebview cant loading base url from documentsURL

Webkit loading from .documentsURL html webpages, iOS device is not showing image, js, css files, works fine on simulators. What could be my bug in the code I have written?
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let documentsURL = URL(fileURLWithPath: documentsPath, isDirectory: true)
let urltostr = documentsURL.absoluteString
//print(urltostr)
let htmlurl = urltostr+"0/index.html"
let finalURL = URL(string: htmlurl)
let base = urltostr+"0/"
let baseUrl = URL(string: base)
//let baseUrl = URL(fileURLWithPath: base, isDirectory: true)
do {
let fileName = try String(contentsOf: finalURL!)
webview.loadHTMLString(fileName as String, baseURL: baseUrl)
} catch {
// catch error
print("Error web view get html")
}

Load image form Gallery in swift from path given by UIImagePickerViewController?

I am saving path in Database return by UIImagepicker from Gallery
let imageURL = info[UIImagePickerControllerReferenceURL] as! NSURL
let imageName = imageURL.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String
//let localPath = documentDirectory.stringByAppendingPathComponent(imageName!)
let imagePath = String("\(documentDirectory)/\(imageName!)")
where path look like
/Users/kshitijghule/Library/Developer/CoreSimulator/Devices/3AC7B500-E980-4A00-BC32-34FA3C7DDE8A/data/Containers/Data/Application/838FB5A1-4448-46C9-8BEC-2E939668B97D/Documents/asset.JPG
Now i want load this image from this path.
i used this code
let url = NSURL(string:"/Users/kshitijghule/Library/Developer/CoreSimulator/Devices/3AC7B500-E980-4A00-BC32-34FA3C7DDE8A/data/Containers/Data/Application/838FB5A1-4448-46C9-8BEC-2E939668B97D/Documents/asset.JPG")!//path from database but mention static
let imageData = NSData(contentsOfURL:url)!
cell?.petImageView.image = UIImage(data: imageData)
But i am getting crash at line
let imageData = NSData(contentsOfURL:url)!
How to fix this issue? It will work on device ?
If you are storing images in the document directory store only image name in the db
At the time of retrieval append the current document directory path with your image name like you done at save time
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String
//let localPath = documentDirectory.stringByAppendingPathComponent(imageName!)
//imageName which you have stored in the db at retrieval time
let imagePath = String("\(documentDirectory)/\(imageName!)")
let url = NSURL(string:imagePath)
let imageData = NSData(contentsOfURL:url)!
as i have also this type of issue at last if found that the app number of simulator(838FB5A1-4448-46C9-8BEC-2E939668B97D) is changes which cause the issue
Hope this may solve your issue
I have answered a similar question here.You only have to save those paths to your database, and from the database path you can retrieve those images.
Save image in Document Directory taken from Gallery or Camera.
func origionalImage(origionalImage: UIImage!, editedImage: UIImage!, userInfo info: [NSObject : AnyObject]!) {
let imageData = NSData(data:UIImagePNGRepresentation(origionalImage)!)
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let docs: String = paths[0]
let imageName = self.randomStringWithLength(6) as String
//imageName can save in sqlite to load image later
let fullPath = String("\(docs)/\(imageName).png")
print(fullPath)
let result = imageData.writeToFile(fullPath, atomically: true)
print("FILE WRITTEN SUCCESS=>:\(result)")
}
Load Image from Database
let tempDBObject = self.petListArray[indexPath.row] as! Database
cell?.petName.text = tempDBObject.Hname
//Doc Path
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String
let imagePath = String("\(documentDirectory)/\(tempDBObject.Hpath!)")
if imagePath == "" {
}else{
cell?.petImageView.image = UIImage(contentsOfFile: imagePath)
}

Counting number of files in Directory with reference counting

I have a folder of images that were imported with Create Folder Reference method, since I want to call images with URLForResoure for transfer to Watch.
Before I transfer Images I would like to count them in folder.
I was able to get folderURL path with this code:
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let folderURL = documentsURL.URLByAppendingPathComponent("Folder/SubFolder", isDirectory: true)
but can not get access to files inside this folder.
I want to access files and count them either with same prefix or inside subfolder.
Please help.
Swift3
let fileManager = FileManager.default
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let dirContents = try? fileManager.contentsOfDirectory(atPath: documentsPath)
let count = dirContents?.count
if count == 0{
disableTabBarHistory()// or whatever...
}
here's a count of directory contents:
let fileManager = NSFileManager.defaultManager()
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var dirContents = try? fileManager.contentsOfDirectoryAtPath(documentsPath)
let count = dirContents?.count
Swift 5.5:
let fileManager = FileManager.default
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let content = try? fileManager.contentsOfDirectory(atPath: path)
let count = content?.count
it's easy my friend
let fileManager = NSFileManager.defaultManager()
var error : NSError?
if let files = fileManager.contentsOfDirectoryAtPath(folde rURL, error: &error) {
let count = files.count
// ...
} else {
println("Could not get contents of directory: \(error?.localizedDescription)")
}
I solved my problem using this line of code:
let URL = NSBundle.mainBundle().URLsForResourcesWithExtension("jpg", subdirectory: "Folder/SubFolder")
let count = (excerciseImagesForAnimationURL?.count)!

Get image from documents directory swift

Say I were using this code to save an image to the documents directroy
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
if paths.count > 0 {
if let dirPath = paths[0] as? String {
let readPath = dirPath.stringByAppendingPathComponent("Image.png")
let image = UIImage(named: readPath)
let writePath = dirPath.stringByAppendingPathComponent("Image2.png")
UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true)
}
}
}
How would I then retrive it? Keeping in mind than in iOS8 the exact path changes often
You are finding the document directory path at runtime for writing the image, for reading it back, you can use the exact logic:
Swift 3 and Swift 4.2
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("Image2.png")
let image = UIImage(contentsOfFile: imageURL.path)
// Do whatever you want with the image
}
Swift 2
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
{
if paths.count > 0
{
if let dirPath = paths[0] as? String
{
let readPath = dirPath.stringByAppendingPathComponent("Image2.png")
let image = UIImage(contentsOfFile: readPath)
// Do whatever you want with the image
}
}
}
Better as an extension.
extension URL {
static var documentsDirectory: URL {
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
return try! documentsDirectory.asURL()
}
static func urlInDocumentsDirectory(with filename: String) -> URL {
return documentsDirectory.appendingPathComponent(filename)
}
}
Used like this:
let path = URL.urlInDocumentsDirectory(with: filename).path
let image = UIImage(contentsOfFile: path)
Load multiple images from the folder or directory. - Swift 4
Here's the image attached to show, what we want to achieve in the given below code.
Here's the code to find the multiple images from the folder in documents directory. I have written one method to do the same.
In the code we are passing the "Folder Name" (ie. Red) and getting the contents of that directory. In return we got the array of images name.
static func loadImagesFromAlbum(folderName:String) -> [String]{
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
var theItems = [String]()
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(folderName)
do {
theItems = try FileManager.default.contentsOfDirectory(atPath: imageURL.path)
return theItems
} catch let error as NSError {
print(error.localizedDescription)
return theItems
}
}
return theItems
}
Here's the result of given code.
Hope it helps.
Thanks
Swift 2
If you want to get a file from your document directory in Swift 2:
let path: String? = NSBundle.mainBundle().pathForResource("imageName", ofType: "png", inDirectory: "DirectoryName/Images")
let imageFromPath = UIImage(contentsOfFile: path!)!
self.myImage.image = imageFromPath
Hope that helps somebody
// --------------------------------------------------------
// MARK:- Document Directory
// --------------------------------------------------------
///# Get Data from document directory #///
private func getDocumentData(){
///# Path #///
let folderPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("MyZipFiles") /// * folder *///
let filePath = URL(fileURLWithPath: folderPath).appendingPathComponent("\(self.id)/\(self.titleVideo)") ///* inside folder all files *///
print(filePath)
///# Get JsonFile from Directory with alamofire #///
let jsonFilePath = URL(fileURLWithPath: folderPath).appendingPathComponent("\(self.id)/\(self.titleVideo)/python.json") ///* inside filename *///
if (try! jsonFilePath.checkResourceIsReachable()) {
print("file exist")
Alamofire.request(jsonFilePath, method: .get, parameters: nil).responseData { (response) in
guard let data = response.data else { return }
do{
let json = try SwiftyJSON.JSON(data: data)
let results = json["images"]
for arr in results.arrayValue{
self.arrImageData.append(Images(json: arr))
}
self._pickerCollectionView.reloadData()
print(self.arrImageData)
}catch{
print(error.localizedDescription)
}
}
///# Back Video #///
let backVideoPath = URL(fileURLWithPath: folderPath).appendingPathComponent("\(self.id)/\(self.titleVideo)/background_video.mp4") ///* inside filename *///
print(backVideoPath)
///# Output Video #///
let outputPath = URL(fileURLWithPath: folderPath).appendingPathComponent("\(self.id)/\(self.titleVideo)/output.mp4")
print(outputPath)
///# Get images string from documentdirectory #///
do {
let imagesData = try FileManager.default.contentsOfDirectory(atPath: filePath.path) ///* Base Path to find Image *///
///# for loop to append path to find saved images and fill image array #///
for imgStr in imagesData{
if imgStr.hasPrefix("img"){
imagesArr.append(imgStr)
print(imagesArr)
let document = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("MyZipFiles")
print(document)
let loadImage = document.appendingPathComponent("\(self.id)/\(self.titleVideo)")
let imgUrl = loadImage.appendingPathComponent(imgStr, isDirectory: true)
print(imgUrl.path)
if let data = UIImage(named: imgStr)?.pngData() ,
!FileManager.default.fileExists(atPath: imgUrl.path){
do{
///* write data to convert string images into url in document folder *///
try data.write(to: imgUrl)
print("Image Add Successfully")
Log.debug(imgStr)
}
catch{
print("Image Not Added")
}
}
///* append written url into array of images *///
imgArr.append(imgUrl)
}
}
}
catch let err{
print(err.localizedDescription)
}
}
}

Resources