How to display image from NSFileManager Url in swift - image

How can I display an image in an UIImageView from
documentsDirectoryURL.URLByDeletingLastPathComponent!.URLByDeletingLastPathComponent!.URLByDeletingLastPathComponent!.URLByAppendingPathComponent("img"))
For example, something like this
imageView.image = UIImage(documentsDirectoryURL.URLByDeletingLastPathComponent!.URLByDeletingLastPathComponent!.URLByDeletingLastPathComponent!.URLByAppendingPathComponent("img")))
This is my documentDirectoryURL
let documentsDirectoryURL = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL

Try this
imageView.image = UIImage(contentsOfFile: documentsDirectoryURL.URLByDeletingLastPathComponent!.URLByDeletingLastPathComponent!.URLByDeletingLastPathComponent!.URLByAppendingPathComponent("img")).path)
Good luck

Related

Swift - saving and retrieving images from userDefaults

I'm trying to save images retrieved from Parse.com like this:
let userImageFile = object["Image"] as PFFile
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData!, error: NSError!) -> Void in
if error == nil {
image = UIImage(data:imageData)
let imageToSave:NSData = UIImagePNGRepresentation(image)
self.saveImage(intRandomNumb, retImage: imageToSave)
}
}
where the saveImage-function looks like this:
func saveImage(imagepath:Int, retImage:NSData){
println("image is being saved")
let defaults = NSUserDefaults.standardUserDefaults()
let imagePathName = "\(imagepath)"
defaults.setObject(retImage, forKey: imagePathName)
}
and later, I'm trying to display this image like this:
var point = gestureRecognizer.locationInView(self.tv)
if let indexPath = self.tv.indexPathForRowAtPoint(point)
{
let data = mainList[indexPath.row] as SecondModel
let fileRef = data.fileReference
let intFileRef = Int(fileRef)
println(intFileRef)
let defaults = NSUserDefaults.standardUserDefaults()
let usedKeyName = "\(intFileRef)"
if let photo = defaults.objectForKey(usedKeyName) as? UIImage {
println("Image created")
let photo = defaults.objectForKey(usedKeyName) as UIImage
var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
imageView.image = photo
self.view.addSubview(imageView)
}
and the "Image created" never gets printed which means the retrieving somehow doesn't work.
I'm not quite sure if you're able to save images to the userdefaults like I've done here, but that was the best I could come up with, and I couldn't find any previous questions like this for Swift.
Any suggestions on how to proceed would be appreciated.
SOLUTION: The problem was that I tried to load the image directly as a UIImage. I also had to convert the NSData to a UIImage, this all happens in the last section of the code displayed above. Finally my code looks like this:
if let photo = defaults.objectForKey("\(intFileRef)") as? NSData {
println("Image created")
let photo = defaults.objectForKey("\(intFileRef)") as NSData
let imageToView:UIImage = UIImage(data: photo)
var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
imageView.image = imageToView
self.view.addSubview(imageView)
}
I hope this can help others struggling with something similar to this.
Swift 3
Hey, try this beautiful code here:
Convert your UIImage to Data.
PNG:
yourDataImagePNG = UIImagePNGRepresentation(yourUIImageHere)
JPEG :
yourDataImageJPG = UIImage(data: yourUIImageHere,scale:1.0)
Save in UserDefaults.
UserDefaults().set(yourDataImagePNG, forKey: "image")
Recover from:
UserDefaults.standard.object(forKey: "image") as! Data
I hope to help!
It seems like you do not call defaults.synchronize() so it's not written to the defaults file.

Creating a Cocoapod library and [UIImage imageNamed:] returns NULL

I have https://github.com/fulldecent/FDChessBoardView working great and am now starting the project again from scratch with pod lib create in order to make a Podspec.
There is one {'.h','.m'} file and some images. The images are in the file system in the provided Pod/Assets folder. The resources are noted in the podspec file with:
s.resource_bundles = {
'FDChessboardView' => ['Pod/Assets/*']
}
(I have also tried directly adding these files into the Development Pods/FDChessboardView/Resources group inside XCode.)
Inside the library implementation file I need to refer to these images. I have tried:
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:#"FDChessboardView" ofType:#"bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
NSString *imagePath = [bundle pathForResource:#"aa" ofType:#"png"];
UIImage* image = [UIImage imageWithContentsOfFile:imagePath];
Here the imagePath is set correctly. This file exists and file confirms it is a PNG:
[...]aa.png: PNG image data, 182 x 164, 8-bit/color RGBA, non-interlaced
However the UIImage is NULL.
I have also tried these:
image = [UIImage imageNamed:#"aa"];
UIImage *image = [UIImage imageNamed:#"FDChessboardView.bundle/aa.png"];
image = [UIImage imageNamed:#"aa" inBundle:bundle compatibleWithTraitCollection:nil];
All of them produce NULL.
Could anyone help point me in the correct direction for how to load theme image assets?
Thank you!
Will
Ok - I found a solution that works for me:
In the lib I am creating, I have the following class: AEBubbleField.h AEBubbleView.m
I also have an image in the Assets folder of the generated file structure called background.png. I want to use this in my lib files above so I add the following to the pod spec (to ensure the png is copied with my lib classes)
s.ios.resource_bundle = { 'AEBubbleField' => 'Pod/Assets/*.png' }
I can then access the image in the following manner:
NSBundle *bundle = [NSBundle bundleForClass:[self class]]; // Any class in the lib can be used here, I just went for the current class
UIImage *backgroundImage = [UIImage imageNamed:#"background.png" inBundle:bundle compatibleWithTraitCollection:nil];
This is the only way I can get the image and use it. All other methods I have tried simply return nil like the original question's.
this answer works for me.
https://stackoverflow.com/a/34324540/1897767
and, my swift code is:
class func loadImage(name: String) -> UIImage? {
let podBundle = NSBundle(forClass: MyClass.self)
if let url = podBundle.URLForResource("MyBundleName", withExtension: "bundle") {
let bundle = NSBundle(URL: url)
return UIImage(named: name, inBundle: bundle, compatibleWithTraitCollection: nil)
}
return nil
}
Rob's answer didn't work for me, I think because I didn't change the resource bundle setup from the default in pod lib create
s.resource_bundles = {
'PodCore' => ['Pod/Assets/*.png',
'Pod/Classes/**/*.xib',
'Pod/Classes/**/*.storyboard']
}
I was able to load images from that resource bundle, but had to define it explicitly.
NSString *bundleURL = [[NSBundle mainBundle] pathForResource:#"PodCore"
ofType:#"bundle"];
NSBundle *podBundle = [NSBundle bundleWithPath:bundleURL];
UIImage *image = [UIImage imageNamed:#"home_black.png"
inBundle:podBundle
compatibleWithTraitCollection:nil];
If you're using Swift 2 > you can access this way:
// should access the bundle for this class
let bundle = NSBundle(forClass: self.classForCoder)
// successfully loaded image
let myImageToUse = UIImage(named: "image", inBundle: bundle, compatibleWithTraitCollection: nil)

UIImageView to UIImage

I have UIImageView contains static image, I want to get this image and set it under UIImage variable.
How can I do that?
UIImageView *imageView = ... // Set from somewhere
UIImage *image = imageView.image; // Get the UIImage.
UIImage *otherImage = [UIImage imageNamed:#"Icon.png"]; // Load another image.
imageView.image = otherImage; // Change in the image in your UIImageView.
UIImageView Class Reference at developer.apple.com

What format is person's ImageData(CFDataRef) in AddressBook?(Jpeg or PNG)?Or how to determine?

From AddressBook's API ABPersonCopyImageData I can get a CFDateRef which is toll-free bridge to NSData. And I want to write this data to file, but what file extension should I use ?
.jpeg or .png?
The documentation doesn't mention what the data is.Is there any way to know?
NSData *imgData = (__bridge NSData *)ABPersonCopyImageData(person);
UIImage *img = [UIImage imageWithData:imgData];
if (!img) {
img = [UIImage imageNamed:#"noImage.png"];
}

iphone: customise cell.accessoryType

hi am doing an iphone twitter app with json and i am wondering if it is possible to set the
cell.accessoryType to a image in UITableView? or possible move the image to the right hand side...any clues?
Sure. Just use the accessoryView property of UITableViewCell and assign a UIImageView:
UIImage *image = [UIImage imageNamed:#"fileNameOfYourImage.jpg"]; //or wherever you take your image from
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
cell.accessoryView = imageView;
[imageView release];
No need to use imageview, just provide this for simple arrow.
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;

Resources