UIImageView image not returning nil but image not showing - uiimageview

I have an image view and it pulls url from the internet this is the url that I got from the RSS Feed -
its an image pulled from rss feed .xml here is code I use to get image.
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *URL = [NSURL URLWithString:#"www.something.com/rss/hi.xml"];
NSData *data = [NSData dataWithContentsOfURL:URL];
// Assuming data is in UTF8.
NSString *string = [NSString stringWithUTF8String:[data bytes]];
NSString *webStringz = string;
NSString *mastaString;
mastaString = webStringz;
NSScanner *theScanner2;
NSString *imageURL2;
theScanner2 = [NSScanner scannerWithString: mastaString];
// find start of tag
[theScanner2 scanUpToString: #"<media:content url=\"" intoString: nil];
if ([theScanner2 isAtEnd] == NO) {
// find end of tag
[theScanner2 scanUpToString: #"\" " intoString: &imageURL2];
imageURL2 = [imageURL2 stringByReplacingOccurrencesOfString:#"<media:content url=\"" withString:#""];
imageURL2 = [imageURL2 stringByReplacingOccurrencesOfString:#"\n" withString:#""];
imageURL2 = [imageURL2 stringByReplacingOccurrencesOfString:#" " withString:#""];
//Download Image
NSURL * imageURL = [NSURL URLWithString:[imageURL2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]])];
UIImage * image = [UIImage imageWithData:imageData];
[imageView setImage:image];
NSLog(#"Image URL #1: %#", imageURL2);
mastaString = [mastaString stringByReplacingOccurrencesOfString:imageURL2 withString:#""];
if (imageView.image == nil) {
NSLog(#"IS NIL");
}
else if (image == nil) {
NSLog(#"IS NIL");
}
// Do any additional setup after loading the view.
}
}
In my NSLOG it says the image url and its valid.
It DOES NOT show the IS NIL
It DOES NOT show the IS NIL 2
But the ImageView is not showing the image? Why? Its all linked up and everything?
Thanks

It must be that you didn't create the image view when the first time you access the view of UIViewController. Note that self.view will trigger viewDidLoad method if it is nil, but then the imageView is nil. So you'b better create the imageView in viewDidLoad method.

Related

Unable to see UIImage once stored and sent to Server form CoreData?

The first part of the code is where the camera button is pressed but not before checking if a textfield has been filled, this then checks camera type. All normal here me thinks.Once the picture has been taken I then resize the image so that its of smaller size then convert it to a NSString to which then the NSString data is stored in CoreData and then sent off to a server to be shown on screen.
This is the camera press button
-(IBAction)takePicture:(UIButton*)sender {
if (printedname.text.length ==0){
UIAlertView*alert=[[UIAlertView alloc]initWithTitle:
#"Please enter Name"message:#""delegate:self cancelButtonTitle:
#"Dismiss"otherButtonTitles:nil];[alertshow];return;
}
UIImagePickerController *pictureTaker = [[UIImagePickerController alloc] init];
pictureTaker.delegate = self;
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeCamera]) {
pictureTaker.sourceType = UIImagePickerControllerSourceTypeCamera;
} else if([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeSavedPhotosAlbum]){
pictureTaker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
}
[self presentViewController:pictureTaker animated:YES completion:nil];}
-(void)imagePickerController:(UIImagePickerController *)pictureTaker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSLog(#"%#", info);
NSString * mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if([mediaType isEqual:(__bridge NSString *)kUTTypeImage]){
[pictureTaker dismissViewControllerAnimated:YES completion:nil];
base64Image = [info objectForKey:UIImagePickerControllerEditedImage];
base64Image = [info objectForKey:UIImagePickerControllerOriginalImage];
CGSize newSize = CGSizeMake(100.0f,60.0f);
UIGraphicsBeginImageContext(newSize);
[base64Image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
base64Image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = UIImageJPEGRepresentation(base64Image, 1.0);
base64string = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSLog(#" image (%#), width: %.0f, height: %.0f, scale: %0.2f, string len %lu",base64Image,base64Image.size.width,
base64Image.size.height, base64Image.scale,(unsigned long)base64string.length);
}
UIImageWriteToSavedPhotosAlbum(base64Image, self, NULL , NULL);
}
It seem to send ok save but kind of get's lost half way through, can anyone help as Iv been >trying to sort this out for days now, Iv included below the console output for you to see >aswell, thanks to anyone that can help.
UIImagePickerControllerMediaType = "public.image";
UIImagePickerControllerOriginalImage = "<UIImage: 0x17056260> size
{ 2448, 3264 }
orientation 3 scale 1.000000";
}
I managed to fix the problem with the code below:
if (self.base64Image!= nil){
NSString *strImageData = [self.base64Image stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSString *param =[NSString stringWithFormat:#"photo=%#", strImageData];
[values addObject:param];
}

How to draw EPS data on NSView

I'm struggling with the problem to draw an eps file on a NSView.
When I first load the eps file from a file and draw it with drawInRect: the image is displayed correctly. However, the image will not be drawn when I load it from an archive file.
I've prepared a dirty small example that you can copy/paste and try out. Create a new Cocoa App project and add this to the delegate method.
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Just a sample eps file
NSURL *url = [NSURL URLWithString: #"http://embedded.eecs.berkeley.edu/concurrency/latex/figure.eps"];
NSImage *epsImage = [[[NSImage alloc] initWithContentsOfURL: url] autorelease];
// Encode data
NSMutableData *mutableData = [[[NSMutableData alloc] init] autorelease];
NSKeyedArchiver *coder = [[[NSKeyedArchiver alloc] initForWritingWithMutableData: mutableData] autorelease];
[coder encodeObject: epsImage forKey: #"image"];
[coder finishEncoding];
NSString *dataFile = [#"~/Desktop/image.data" stringByExpandingTildeInPath];
[mutableData writeToFile: dataFile atomically: YES];
// Decode data
NSData *data = [NSData dataWithContentsOfFile: dataFile];
NSKeyedUnarchiver *decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData: data];
NSImage *loadedImage = [decoder decodeObjectForKey: #"image"];
// Draw image
NSRect rect;
rect.origin = NSZeroPoint;
rect.size = loadedImage.size;
NSView *view = [[NSApp mainWindow] contentView];
[view lockFocus];
[loadedImage drawInRect: rect fromRect: rect operation: NSCompositeSourceOver fraction: 1.0];
[view unlockFocus];
}
To prove that the first loaded image draws correctly just change the line [loadedImage drawInRect:...] to [epsImage drawInRect:...].
I'm using NSKeyedArchiver and NSKeyedUnarchiver here for simulating encodeWithCoder: and initWithCoder:. So please focus on the fact that NSImage with NSEPSImageRep representation, which does not contain a preview (from a resource fork?) and loaded purely as eps commands, is not drawn on a NSView correctly.
Any help is appreciated.
Due to the way that cacheing works on NSImage, I've often found it more effective to actually grab the NSImageRep if I know what the type is.
In our code, we found that the most reliable way to save off images is in their original format, but that requires either saving off the data in its original format somewhere else, or requesting the data from the NSImageRep. Unfortunately, there's not a generic -(NSData*)data method of NSImageRep, so we ended up specifically checking for various types of NSImageRep and saving them off depending on what we knew them to be.
Fortunately, loading is simple, as NSImage::initWithData: will figure out the type based on the data.
Here's our long-standing code for doing this. Basically, it prefers PDF then EPS then it makes a TIFF of anything it doesn't understand.
+ (NSData*) dataWithImage:(NSImage*)image kindString:( NSString**)kindStringPtr
{
if (!image)
return nil;
NSData *pdfData=nil, *newData=nil, *epsData=nil, *imageData=nil;;
NSString *kindString=nil;
NSArray *reps = [image representations];
for (NSImageRep *rep in reps) {
if ([rep isKindOfClass: [NSPDFImageRep class]]) {
// we have a PDF, so save that
pdfData = [(NSPDFImageRep*)rep PDFRepresentation];
PDFDocument *doc = [[PDFDocument alloc] initWithData:pdfData];
newData = [doc dataRepresentation];
if (newData && ([newData length]<[pdfData length])) {
pdfData = newData;
}
break;
}
if ([rep isKindOfClass: [NSEPSImageRep class]]) {
epsData = [(NSEPSImageRep*)rep EPSRepresentation];
break;
}
}
if (pdfData) {
imageData=pdfData;
kindString= #"pdfImage";
} else if (epsData) {
imageData=epsData;
kindString=#"epsImage";
} else {
// make a big copy
NSBitmapImageRep *rep0 = [reps objectAtIndex:0];
if ([rep0 isKindOfClass: [NSBitmapImageRep class]]) {
[image setSize: NSMakeSize( [rep0 pixelsWide], [rep0 pixelsHigh])];
}
imageData = [image TIFFRepresentation];
kindString=#"tiffImage";
}
if (kindStringPtr)
*kindStringPtr=kindString;
return imageData;
}
Once we have the NSData*, it can be saved in a keyed archive, written to disk or whatever.
On the way back in, load in the NSData* and then
NSImage *image = [[NSImage alloc] initWithData: savedData];
and you should be all set.

cocoa nsimage does not get saved

I'm new to cocoa and programming, sorry if this is something basic.
I'm using ARC. I have an NSImageView component, which is controlled by DropZone class. I drag & drop an image into it, but once I try to call in the scalling method I got, it tells me that the ": ImageIO: CGImageSourceCreateWithData data parameter is nil" I assume I'm doing something wrong, just don't know what yet.
Here's my method in DropZone.m
- (void)scaleIcons:(NSString *)outputPath{
NSImage *anImage;
NSSize imageSize;
NSString *finalPath;
anImage = [[NSImage alloc]init];
anImage = image;
imageSize = [anImage size];
imageSize.width = 512;
imageSize.height = 512;
[anImage setSize:imageSize];
finalPath = [outputPath stringByAppendingString:#"/icon_512x512.png"];
NSData *imageData = [anImage TIFFRepresentation];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:imageData];
NSData *dataToWrite = [rep representationUsingType:NSPNGFileType properties:nil];
[dataToWrite writeToFile:finalPath atomically:NO];
}
The DropZone.h
#interface DropZone : NSImageView <NSDraggingDestination>{
NSImage *image;
}
- (void)scaleIcons:(NSString *)outputPath;
#end
And here's how I call it it my AppDelegate.m
- (IBAction)createIconButtonClicked:(id)sender {
NSFileManager *filemgr;
NSString *tempDir;
filemgr = [NSFileManager defaultManager];
tempDir = [pathString stringByAppendingString:#"/icon.iconset"];
NSURL *newDir = [NSURL fileURLWithPath:tempDir];
[filemgr createDirectoryAtURL: newDir withIntermediateDirectories:YES attributes: nil error:nil];
DropZone *myZone = [[DropZone alloc] init];
[myZone scaleIcons:tempDir];
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:#"Done!"];
[alert runModal];
}
the image get's pulled from the pastebaord:
- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender{
if ([NSImage canInitWithPasteboard:[sender draggingPasteboard]]) {
image = [[NSImage alloc]initWithPasteboard:[sender draggingPasteboard]];
[self setImage:image];
[self setImageAlignment: NSImageAlignCenter];
}
return YES;
}
For some reason my "image" gets lost. Could somebody help?
The problem is that you're creating a new instance of DropZone in your app delegate, but I'm assuming that you created the image view in IB and changed its class to DropZone. Is that correct? If so, you need to have an IBOutlet in the app delegate connected to the image view in IB, and have this:
[self.iv scaleIcons:tempDir];
where iv is my IBOutlet.
Without knowing where "image" comes from, I would say your problem is in these lines...
anImage = [[NSImage alloc]init];
anImage = image;
You should just grab the image from the imageView...
anImage = [myImageView image];

How do I add a NSError check with initWithContentsOfFile when looking for an image?

In my app, the user can save an image to their documents directory. At launch, I grab the image, add a border, and put it into a UIImageview like this....
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/ImageOne.jpg", docDirectory];
UIImage *unborderedImage = [[[UIImage alloc] initWithContentsOfFile:filePath] autorelease];
//image found....add border
UIImage *imageWithBorder = [self addBorderToImage:unborderedImage];
imageOneView.image = imageWithBorder;
Ideally, I like to check that the image is there first before adding a border. If not, load an "image not available" placeholder. Something like this:
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/ImageOne.jpg", docDirectory];
UIImage *unborderedImage = [[[UIImage alloc] initWithContentsOfFile:filePath] autorelease];
NSError * error;
if (error != nil) {
//image found....add border
UIImage *imageWithBorder = [self addBorderToImage:unborderedImage];
imageOneView.image = imageWithBorder;
} else
//no image saved
[imageOneView setImage:[UIImage imageNamed:#"photoNotAvailable.png"]];
}
Of course, this doesn't work. I just can't seem to figure out how handle if "ImageOne.jpg" isn't found.
As it turns out, I need to do other things with the image elsewhere within the app. This would also depend on whether or not the user had saved an image or not. So in my method where the user can save the image, I send out a NSNotification that the image has changed. Then on my MainView, I look for the notification and key off that.
When saved:
[collectionOneUserDefinedDefaults setObject:#"image added" forKey:#"collectionOneImageAdded"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"collectionOneImageChanged" object:self];
Then in my MainView I look for the notification:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(updateCollectionOneImage) name:#"collectionOneImageChanged" object:nil];
- (void)updateCollectionOneImage {
//check if an image was ever saved, if so, replace the noPhotoAvailalble placeholder
NSUserDefaults *collectionOneUserDefinedDefaults = [NSUserDefaults standardUserDefaults];
NSString *collectionOneImageTextString = [collectionOneUserDefinedDefaults stringForKey:#"collectionOneImageAdded"];
if (collectionOneImageTextString == nil || [collectionOneImageTextString isEqualToString:#""]) {
[collectionOneImage setImage:[UIImage imageNamed:#"photoNotAvailable.png"]];
}
else {
//pull in collection one image from the Documents folder
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/CollectionOneImage.jpg", docDirectory];
UIImage *unborderedImage = [[[UIImage alloc] initWithContentsOfFile:filePath] autorelease];
//image found....add border
UIImage *imageWithBorder = [self addBorderToImage:unborderedImage];
collectionOneImage.image = imageWithBorder;
}
}
It works perfectly. It in turn builds in the error handling. If the user saved and image, it gets loaded. If not, a placeholder image is loaded.
Your error handling here is doing nothing and is misguided. All you need do is simply check if unborderedImage is nil or not.

Copy partial screenshot to Pasteboard

So, the code to copy part of my screen to the pasteboard works because it was successfully coping it to my photo album. But, I want to be able to paste the partial screenshot into a new SMS message. I know it will have to be done manually (long hold on message and Paste), but it either pasted nothing, or does not have the Paste option (as it's saving it as a String). The middle portion of the code is the part I'm struggling with. Any help would be great. I've changed the forPasteboardType to "image" but that does not work either.
//Capture part of Screen Shot
UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(c, 0, 98); //
[self.view.layer renderInContext:c];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//Send Screenshot to Pasteboard
UIPasteboard *pasteBoard = [UIPasteboard pasteboardWithName:UIPasteboardNameGeneral create:YES];
pasteBoard.persistent = YES;
NSData *data = UIImagePNGRepresentation(viewImage);
[pasteBoard setData:data forPasteboardType:(NSString *)kUTTypePNG];
/////// Open SMS
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
controller.body = #"Hello from me, paste image here -->";
controller.recipients = [NSArray arrayWithObjects:#"123456789", nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
////// End SMS
}
//Capture part of Screen Shot
UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(c, 0, 98); //
[self.view.layer renderInContext:c];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//Send Screenshot to Pasteboard
UIPasteboard *pasteBoard = [UIPasteboard pasteboardWithName:UIPasteboardNameGeneral create:YES];
pasteBoard.persistent = YES;
NSData *data = UIImagePNGRepresentation(viewImage);
[pasteBoard setData:data forPasteboardType:(NSString *)kUTTypePNG];
NSString *stringURL = #"sms:";
NSURL *url = [NSURL URLWithString:stringURL];
[[UIApplication sharedApplication] openURL:url];

Resources