I understand that to get images from the asset catalog i can use UIImage(named: "fileName") to do it.
however, what if i am getting DATA from the XCAsset catalog? I can't figure this out.
I have tried,
let url = NSBundle.mainBundle().URLForResource("fileName", withExtension: nil)
let data = NSData(contentsOfURL: url!)
But it is nil. I do not know how to get data from the XCAssets catalog. If anyone can help me out (googling hasn't helped) please let me know I will be very thankful!
Update:
Why am I trying to get data from an asset catalog? I dragged an animated gif into the asset catalog. And the asset catalog interprets that as DATA. This is why I am trying to get data out of the asset catalog.
Update:
This is a screen shot of my Assets.xcassets folder looks like.
It has a file called "_Loading" and on the right it is considered a "Data set".
I'm not sure how to get the data set from the Assets catalog.
I am going to answer my own question.
Since iOS 9, the Asset Catalog allows more than just Images. They allow Data sets. In order to get data from the Asset Catalog, you must use the NSDataAsset class.
Example: Assume you have an Data Asset named "CoolJSON"
if let asset = NSDataAsset(name: "CoolJSON") {
let data = asset.data
let d = try? NSJSONSerialization.JSONObjectWithData(data, options: [])
}
In this example I turned an NSData object into a json.
NSDataAsset class reference
Load gif image from Assets.xcassets file. That`s same for loading json files.
NEW: 【New Data Set】 crate a data set and rename "funny" in Assets.xcassets folder. all right, the gif file is added to Assets.xcassets folder.
USE:
NSDataAsset *asset = [[NSDataAsset alloc] initWithName:#"funny"];
self.gifImageView.image = [UIImage sd_animatedGIFWithData:asset.data];
(UIImage *)sd_animatedGIFWithData:(NSData *)data: is a UIImage+GIF category for loading gif image in SDWebImage.
Related
I've searched and found some ways where I can get the video asset/file of the LivePhoto asset. But what those methods do are as follows:
They somehow get the resources(PHAssetResource) for the LivePhoto asset
Select the specific video resource(PHAssetResource) from previously found resources.(Ex: resource.type==PHAssetResourceTypePairedVideo)
Save the resource data to a new File(!)
Get the URL for the newly created File.
But, what I want to know, is there any way I can get the URL for the originally stored file URL, without creating a new File?
[For other types of photos/videos I'm able to get the URLs of the originally stored files. The problem is with the video of the LivePhoto asset.]
I have found a way to directly get the original URL of the file. There is no need to save the file contents in a new file. (Tested on iOS12+)
We first get the file URL of associated Image of the LivePhoto.
asset.requestContentEditingInput(with: nil) { (editingInput, info) in
if let input = editingInput, let imgUrl = input.fullSizeImageURL {
// use imgUrl
}
}
The Video file is stored in the same directory as the image file. So, we use the Image URL but with different extension to find the Video file of the LivePhoto. The video file extension is either .mov or .MOV.
if let videoPath = (imagePath.deletingPathExtension as NSString).appendingPathExtension("MOV") {
let videoUrl = URL(fileURLWithPath: videoPath)
// check if file exist and use
// If MOV(Uppercase) extension file doesn't exist check for mov(lowercase) extension similarly
}
I'm an undergraduate student and I'm witring an iPhone HumanSeg app. But now I have a problem, that I have a native video in album, and I need to load that video into my code and do some processing. My codes are below:
let filePath = Bundle.main.path(forResource: "1", ofType: "mp4")
let videoURL = NSURL(fileURLWithPath: filePath!)
let avAsset = AVAsset(url: videoURL as URL)
But when I run this code, Xcode just tells me that filePath is nil. I assert that 1.mp4 is in both Assets.xcaassets and iPhone album. Is there anyone who'd like to offer some help?
By the way, How can I get the images(in UIImage format) in the video at the fastest speed? For each image at given time, I really have to read it in no more than 5ms so I may output the preserved video at a good fps.
Check target's build phases, whether the file is being copied to the bundle.Also the check the box to include the file. This code is correct for fetching that file.
I'm currently storing my images directly in core data and experiencing issues when having to retrieve a high quality images.
I was advised to store the images in the document directory and save a path in core-data as to not store the actual images there but simply the address of where I can go and find it.
Can someone push me in the right direction? Can't seem to find the appropriate guidance?
I was able to find the answers to all my questions in this youtube video -
https://www.youtube.com/watch?v=6vk4UrJR8WM
This is the github with the file that has instructions as to how to complete this - https://github.com/TDAbboud/WeightLogger-Images
Try Hanake cache: https://github.com/Haneke/Haneke
It worked really well for me personally with the same problem. It makes a sometimes painful task pretty easy.
Save an image in Document directory is easy this code is not optimized is just for give you a hint( you should manage errors, optionals etc). Suppose that you already have a valid UIImage instance called image and a valid image name String called imageName
let data = UIImagePNGRepresentation(image)
// Unwrapping the data optional
if let data = data {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let path = (paths.first! as! NSString).stringByAppendingPathComponent(imageName)
data.writeToFile(path, options: [])
//Save the path into your managed object
}
I can't figure out how to display an image "HappyFace.png" in a WebView when the image is inside the Assets.xcassets folder.
Instead, I'm forced to store the image in the same location (same level) as the Assets.xcassets file and other dot swift files. As long as I store it there, I can refer to it by name:
let htmlString: NSString = "<html><body><img src='HappyFace.png'/></body></html>"
let path: NSString = NSBundle.mainBundle().bundlePath
let baseURL: NSURL = NSURL(fileURLWithPath: path as String)
MyWebView.loadHTMLString(htmlString as String, baseURL: baseURL)
Does anyone know how to access the images in xcassets? Is it even appropriate to store my image there? (It's not an app icon, nor a loading screen image, maybe it doesn't belong under xcassets?).
Snapshot of My File Hierarchy
There is no simple way to do this. You must either store the images outside XCAssets and reference them as you have done, or unpack XCAssets into a local directory.
This question includes a useful summary, and one answer demonstrates how to achieve this using a custom URL protocol.
In my code I managed to save a textLabel with CoreData but I can't seem to properly save the image. I've read some tutorials and I know I have to convert it to NSData. But how do I do it?
Thanks in advance!
You shouldn't save large data inside core data, an Apple engineer told me this little trick at the last WWDC:
You can use the property "Allows external storage":
By doing this as far as i know, your image will be stored somewhere in the file system, and inside core data will be saved a link to your picture in the file system. every time you'll ask for the picture, core data will automatically retrive the image from the file system.
To save the image as NSData you can do:
let image = UIImage(named: "YourImage")
let imageData = NSData(data: UIImageJPEGRepresentation(image, 1.0))
managedObject?.setValue(imageData, forKey: "YourKey")
Remember that 1.0 in the UIImageJPEGRepresentatio means that your using the best quality and so the image will be large and heavy:
The quality of the resulting JPEG image, expressed as a value from 0.0
to 1.0. The value 0.0 represents the maximum compression (or lowest
quality) while the value 1.0 represents the least compression (or best
quality).
Core Data isn't meant to save big binary files like images. Use Document Directory in file system instead.
Here is sample code to achieve that.
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
// self.fileName is whatever the filename that you need to append to base directory here.
let path = documentsDirectory.stringByAppendingPathComponent(self.fileName)
let success = data.writeToFile(path, atomically: true)
if !success { // handle error }
It is recommended to save filename part to core data along with other meta data associated with that image and retrieve from file system every time you need it.
edit: also note that from ios8 onwards, persisting full file url is invalid since sandboxed app-id is dynamically generated. You will need to obtain documentsDirectory dynamically as needed.
Here you go for JPEG and for PNG you just use UIImagePNGRepresentation:
let image = UIImage(named: "YourImage")
let imageData = NSData(data: UIImageJPEGRepresentation(image, 1.0))
managedObject?.setValue(imageData, forKey: "YourKey")
Generally large data objects are not stored in a database or Core Data. Instead save the images in the Document directory (or a sub-directory) and save the file name in Core Data.
Se the answer by #Valentin on how to create a data representation of an image.
Save it with func writeToFile(_ path: String, atomically atomically: Bool) -> Bool