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

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];
}

Related

UIImageView image not returning nil but image not showing

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.

Cocos2d V3 can't switch scenes after using the UIImagePickerController Class

I'm having a little trouble switching scenes (or even displaying sprites) on my CCscene UserLevelCreation, but it only happens after i use the UIImagePickerController to take/accept a picture, And then when I try to switch scenes, It crashes with the error:
"Could not attach texture to framebuffer"
this is the code I use to take a picture:
-(void)takePhoto{
AppController *appdel = (AppController*) [[UIApplication sharedApplication] delegate];
#try {
uip = [[UIImagePickerController alloc] init] ;
uip.sourceType = UIImagePickerControllerSourceTypeCamera;
uip.allowsEditing = YES;
uip.delegate = self;
}
#catch (NSException * e) {
uip = nil;
}
#finally {
if(uip) {
[appdel.navController presentModalViewController:uip animated:NO];
}
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSString * LevelImage;
LevelImage=[info objectForKey:UIImagePickerControllerOriginalImage];
AppController *appdel = (AppController*) [[UIApplication sharedApplication] delegate];
[appdel.navController dismissModalViewControllerAnimated:YES];
[NSThread detachNewThreadSelector:#selector(writeImgToPath:) toTarget:self withObject:LevelImage];
}
And the WriteImageToPath function:
-(void)writeImgToPath:(id)sender
{
UIImage *image = sender;
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
CGSize size;
int currentProfileIndex = 1;
NSString *path = [[pathArr objectAtIndex:0]
stringByAppendingPathComponent:[NSString stringWithFormat:#"CustomLevel_%d.png",currentProfileIndex]];
size = CGSizeMake(1136, 640);
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, 1136, 640)];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
CCLOG(#"saved...");
CGRect r = CGRectMake(0, 0, 1136, 640);
UIGraphicsBeginImageContext(r.size);
UIImage *img1;
[image drawInRect:r];
img1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(img1, nil, nil, nil);
currentProfileIndex++;
[[CCDirector sharedDirector] replaceScene:[LevelEditor Scene]
withTransition:[CCTransition transitionPushWithDirection:CCTransitionDirectionLeft duration:1.0f]];
}
-UPDATE----------------------------------------------------------------------------------
I just tried switching scenes in different places in the code, and I can switch scenes freely until the Function:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
I think that function might be the problem.
So far, I have tried to:
1.switch scenes before taking the picture, and that works fine
2.I read that it might be because i was resizing the image, but commenting that out made no difference.
3.I've also added breakpoints before the scene switch, and the scene isn't nil
4.Finally i tred dismissing the uip UIImagePickerController, but that made no difference either.
Sorry for the long post /: if anyone knows whats going on any help would be really great.
Ok so I found the problem to be this line:
[NSThread detachNewThreadSelector:#selector(writeImgToPath:) toTarget:self withObject:LevelImage];
}
Apparently some Parts of Uikit are not thread-friendly, so I'm now using just
[self writeImgToPath];
And it works, hope this helps anyone with the same problem.

Storing a PDF generated 'on the fly' for iPad on IOS6.1

I am trying to create a PDF report from an iPad app using xcode 4.6. I know a valid pdf file is being created when run on the simulator, because I can dig it out and preview it. The commented out code does this. The problem is that I can't write it somewhere I can get at it on the iPad.
I've tried using UIGraphicsBeginPDFContextToData instead and trying to write the image out to the PhotoAlbum instead. The problem here is that when I convert the NSMutableData into an image it returns nil.
Here is the code. Thanks for any help you can give me.
- (IBAction)makePDF:(UIButton *)sender
{
CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, (CFStringRef)self.labelCopyright.text, NULL);
if (currentText)
{
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);
if (framesetter)
{
// NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, //NSUserDomainMask, YES) objectAtIndex:0];
// NSString *pdfPath = [rootPath stringByAppendingPathComponent:#"Nick.pdf"];
// NSLog(#"pdf is at %#",pdfPath);
// UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
NSMutableData *data = [[NSMutableData alloc] initWithCapacity:100000];
UIGraphicsBeginPDFContextToData(data, CGRectZero, nil);
CFRange currentRange = CFRangeMake(0, 0);
NSInteger currentPage = 0;
BOOL done = NO;
do
{
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
currentPage++;
// [self drawPageNumber:currentPage];
currentRange = [self renderPage:currentPage withTextRange:currentRange andFramesetter:framesetter];
if (currentRange.location == CFAttributedStringGetLength((CFAttributedStringRef)currentText)) done = YES;
}
while (!done);
UIGraphicsEndPDFContext();
UIImage* image = [UIImage imageWithData:data];
assert(image);
UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
CFRelease(framesetter);
}
else NSLog(#"Could not create the framesetter needed to lay out the atrributed string.");
CFRelease(currentText);
}
else NSLog(#"Could not create the attributed string for the framesetter");
}
- (CFRange)renderPage:(NSInteger)pageNum withTextRange:(CFRange)currentRange andFramesetter:(CTFramesetterRef)framesetter
{
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
CGRect frameRect = CGRectMake(72, 72, 468, 648);
CGMutablePathRef framePath = CGPathCreateMutable();
CGPathAddRect(framePath, NULL, frameRect);
CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
CGPathRelease(framePath);
CGContextTranslateCTM(currentContext, 0, 792);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CTFrameDraw(frameRef, currentContext);
currentRange = CTFrameGetVisibleStringRange(frameRef);
currentRange.location += currentRange.length;
currentRange.length = 0;
CFRelease(frameRef);
return currentRange;
}
Save the mutable data to your documents directory
[data writeToFile:filePath atomically:YES]
Here's an example:
+(void) saveData: (NSData*) data ToFileName: (NSString*) filename {
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent: filename];
// instructs the mutable data object to write its context to a file on disk
[data writeToFile:documentDirectoryFilename atomically:YES];
//NSLog(#"documentDirectoryFileName: %#",documentDirectoryFilename);
}
As for displaying the generated PDF on the device, the UIWebView object supports loading PDF files from NSData. Here is an example:
[self.webView loadData:pdfData MIMEType:#"application/pdf" textEncodingName:#"utf-8" baseURL:nil];
It is possible to attach an NSData object to an email as well. Here is an example:
//Check if we can send e-mails
if ([MFMailComposeViewController canSendMail]) {
//Create the Email view controller
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
//Set the subject and body
[controller setSubject:#"Email Subject"];
[controller setMessageBody:#"Email body" isHTML:NO];
//Set the email address
[controller setToRecipients:#"test#test.com"];
//Add the current PDF as an attachment
NSString *fileName = #"file.pdf";
[controller addAttachmentData:self.retrievedPDF mimeType:#"application/pdf" fileName:fileName];
// show the email controller modally
[self.navigationController presentModalViewController: controller animated: YES];
}
Instead of writing the PDF to an NSMutableData object, write it to a file using UIGraphicsBeginPDFContextToFile.
The first argument is the file path. The best place would be the Documents directory. There are then many different ways to get the file out of the app:
iTunes file sharing
Email
iCloud
Sending to a 3rd party server (Dropbox, Box, Google Drive, etc.)
Open in another iOS app using UIDocumentInteractionController.

Posting images from camera roll to facebook in xcode 4.5

I've got some functionality set up. But I'm lost on where to go from here. I can probably figure out what to do with facebook once I know how to actually use the images. I tried saving the image into NSDictionary and then redirecting to a different View Controller, but it won't let me redirect from within the imagePickerController method. So anybody have any idea how to use the image selected from camera roll?
My next idea was to save it in the NSDictionary and then just have a statement checking to see if the NSdictionary value changed but that's not an efficient way of doing it at all.
EDITED below to include the answer provided, but nothing happens, no image displays or anything. What am I missing?
- (void) useCameraRoll
{
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imagePicker =
[[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType =
UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = [NSArray arrayWithObjects:
(NSString *) kUTTypeImage,
nil];
imagePicker.allowsEditing = NO;
[self presentModalViewController:imagePicker animated:YES];
[imagePicker release];
newMedia = NO;
}
}
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info
objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *image = [info
objectForKey:UIImagePickerControllerOriginalImage];
NSLog(#"image:%#",image);
displayPhoto.image = image;
[displayPhoto setFrame:CGRectMake(0, 0, 320, 480)];
[[self view] addSubview:displayPhoto];
}
else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
{
// Code here to support video if enabled
}
}
Assuming you have called this from a view controller with a button that you have created, why not just add a UIImageView onto your view controller? Call it myPhotoImageView or something like that and then in the didFinishPickingMediaWithInfo method, just add the following line of code after
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
as
myPhotoImageView.image = image;
To size the image view so that the aspect looks nice do this.
CGSize size = image.size;
CGRect photoFrame;
if (size.width > size.height)
{
// Landscape
CGFloat scaleFactor = 320 / size.width;
photoFrame = CGRectMake(0, 0, 320, size.height*scaleFactor);
}
else
{
// Portrait
CGFloat scaleFactor = 320 / size.height;
photoFrame = CGRectMake(0, 0, size.width*scaleFactor, 320);
}
myPhotoImageView.frame = photoFrame;

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