-writeToURL is not overwriting the previous write - ios

UPDATE #1: forgot to mention this is running on an iPad app
This is my revised code (still not working, but got rid of the unnecessary code):
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:#"custImage"] URLByAppendingPathExtension:#"png"];
NSError*writeError = nil;
[client.aClientImage writeToURL:fileURL options:0 error:&writeError];
NSAssert(writeError==nil, writeError);
// write appointment info
NSString *htmlString;
if(client.aClientEMail.length > 0) {
htmlString = [NSString stringWithFormat:NSLocalizedString(#"HTML_STRING1",nil),
client.aClientFirstName,
client.aClientLastName,
client.aClientEMail.length == 0? #"": client.aClientEMail,
client.aClientPrimaryPhone,
apptSelected.aServices,
fileURL];
}
else {
htmlString = [NSString stringWithFormat:NSLocalizedString(#"HTML_STRING2",nil),
client.aClientFirstName,
client.aClientLastName,
client.aClientPrimaryPhone,
apptSelected.aServices,
fileURL];
}
When I look at custImage in the XCode debugger, I see a different image from the previous image, which is correct. However, when it gets time to display the image at fileURL, it's a totally different image than custImage and is the same image that was displayed the first time!
UPDATE #2: I have figured out that fileURL has the correct image, but it is NOT being written to the device the second time (the first image is not being replaced).
UPDATE #3: this is the contents of htmlString that is displayed in the UIWebView popover:
<html><head><style type="text/css"> body {font-family: "Verdana"; font-size: 12;} </style></head><body>
<h2>Rolf Marsh</h2><p>phone: 213-555-1234<p>services: Art, Decals<p><img src="file:///private/var/mobile/Applications/FEE7159E-1FF8-4B94-A446-2A4C72E0AD41/tmp/custImage.png"/></body></html>
Any suggestions on how to fix this?

you never write the data to disk as far as I can see.
Only in the commented out section you attempt to.
Write it in between:
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:#"custImage"] URLByAppendingPathExtension:#"png"];
//write
NSError*writeError = nil;
[client.aClientImage writeToURL:fileURL options:0 error:&writeError];
NSAssert(writeError==nil, writeError);
//read / use in the html or so
...
Dont forget to reload the web view or whatever you use to show the html

I figured it out... for others that are having the same problem, here is the code that works. Notice that I do NOT save it to a temporary file, since I already have the image in the Core Data entity. Here's the code:
-(void) showExistingAppointmentDetails: (AppointmentInfo *) apptSelected {
// make rectangle to attach popover
CGRect rectangle = CGRectMake( [apptSelected.aPosX floatValue], [apptSelected.aPosY floatValue],
[apptSelected.aPosW floatValue], [apptSelected.aPosH floatValue]);
// see if this is for staff; if so, don't display anything
if([apptSelected.aApptKey isEqual: #"Staff"])
return;
NSPredicate *predicate = ([NSPredicate predicateWithFormat: #"aClientKey == %#", apptSelected.aApptKey ]); // was aApptKey
ClientInfo *client = [ClientInfo MR_findFirstWithPredicate:predicate inContext:localContext];
UIImage *image = [UIImage imageWithData:client.aClientImage]; // image is good <---------
// write appointment info into html string
NSString *htmlString;
if(client.aClientEMail.length > 0) {
htmlString = [NSString stringWithFormat:NSLocalizedString(#"HTML_STRING1",nil),
client.aClientFirstName,
client.aClientLastName,
client.aClientEMail.length == 0? #"": client.aClientEMail,
client.aClientPrimaryPhone,
apptSelected.aServices,
[self htmlForPNGImage:image]];
}
else {
htmlString = [NSString stringWithFormat:NSLocalizedString(#"HTML_STRING2",nil),
client.aClientFirstName,
client.aClientLastName,
client.aClientPrimaryPhone,
apptSelected.aServices,
[self htmlForPNGImage:image]];
}
UIViewController* popoverContent = [[UIViewController alloc] init];
UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 250, 300)];
popoverView.backgroundColor = [UIColor colorWithWhite:(CGFloat)1.0 alpha:(CGFloat)1.0]; // frame color?
popoverContent.view = popoverView;
//resize the popover view shown in the current view to the view's size
popoverContent.contentSizeForViewInPopover = CGSizeMake(250, 300);
// add the UIWebView for RichText
UIWebView *webView = [[UIWebView alloc] initWithFrame:popoverView.frame];
webView.backgroundColor = [UIColor whiteColor]; // change background color here
// add the webView to the popover
[webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:nil]];
[popoverView addSubview:webView];
// if previous popoverController is still visible... dismiss it
if ([popoverController isPopoverVisible]) {
[popoverController dismissPopoverAnimated:YES];
}
//create a popover controller
popoverController = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
[popoverController presentPopoverFromRect:rectangle inView:self
permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
- (NSString *) htmlForPNGImage:(UIImage *) image {
NSData *imageData = UIImagePNGRepresentation(image);
NSString *imageSource = [NSString stringWithFormat:#"data:image/png;base64,%#",[imageData base64Encoding]];
return [NSString stringWithFormat:#"%#", imageSource];
}

Related

How to zoom and swipe multiple images coming from webservise in objective c

1) In my application, I want to zoom and pinch an image. In xib file, there is a imageView inside a scrollview.Page control is used for swiping images. For a single image it gets zoomed, but for multiple images(coming from web service) it is not getting swipe and zoom.
In setMultipleImages method, images are not getting zoomed and swiped, while if image is single it gets zoom properly.
2) In UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]]; line code, want to replace uiimage with uiimageview. How can I do it?
My code is:
-(void)setMultipleImages{
for (int i = 0; i < [imageMArray count]; i++){
NSString *logoName;
NSArray *imageNameArray = [[imageMArray objectAtIndex:i] componentsSeparatedByString:#"/"];
logoName = [[NSString alloc]initWithFormat:#"%#",[imageNameArray lastObject]];
if (![[AppDelegateHelper getInstance] fileExist:logoName])
{
NSString *imageURL = [[NSString alloc]initWithFormat:#"%#%#",[UrlBuilder getWebsiteUrl],[imageMArray objectAtIndex:i]];
[self startProcessing];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];
[activityIndicator stopAnimating];
DebugLog(#"%f,%f",image.size.width,image.size.height);
NSArray *docDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [docDir objectAtIndex:0];
DebugLog(#"saving png");
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#",cacheDirectory,[imageNameArray lastObject]];
NSData *data1 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
[data1 writeToFile:pngFilePath atomically:YES];
}
}
[self loadImageData];
}
-(void)loadImageData
{
int X =0;
for (int s=0; s<imageMArray.count; s++) {
NSString *logoName;
NSArray *imageNameArray = [[imageMArray objectAtIndex:s] componentsSeparatedByString:#"/"];
logoName = [[NSString alloc]initWithFormat:#"%#",[imageNameArray lastObject]];
if([[AppDelegateHelper getInstance] loadImage:logoName] != nil)
{
// UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(X, 0, scrollView.frame.size.width, 300)] ;
[imageView setImage:[[AppDelegateHelper getInstance] loadImage:logoName]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[scrollView addSubview: imageView];
X = X + imageView.frame.size.width;
}
else
{
//UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(X, 0, scrollView.frame.size.width, 300)] ;
[imageView setImage:[UIImage imageNamed:#"NoImage.png"]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[scrollView addSubview: imageView];
X = X + imageView.frame.size.width;
}
}
self.pageControl.numberOfPages = [imageMArray count];
scrollView.contentSize = CGSizeMake(X,scrollView.frame.size.height);
lblCount.text = [[NSString alloc]initWithFormat:#"1 sur %lu",(unsigned long)imageMArray.count];
}
Add all your images to imageview. Then apply pinchguesture to images view for zoom effect.
Pinch Guesture:
UIPinchGestureRecognizer *imageviewguesture=[[UIPinchGestureRecognizer alloc]initWithTarget:self action:#selector(ImageViewPinchGuesture:)];
add pinch guesture to your image view:
[YourImageView addGestureRecognizer:imageviewguesture];
Make your selector method:
-(void)ImageViewPinchGuesture:(UIPinchGestureRecognizer *)pinGuestureregonizer{
pinGuestureregonizer.view.transform = CGAffineTransformScale(pinGuestureregonizer.view.transform, pinGuestureregonizer.scale, pinGuestureregonizer.scale);
pinGuestureregonizer.scale = 1;
}
In your .h file add this line
-(void)ImageViewPinchGuesture:(UIPinchGestureRecognizer *)pinGuestureregonizer;
To check effect in simulator Press Cmd+alt then press left mouse pad button and drag.
Hope this will Help. Don't forget to accept the answer if it helps you.

Setting subviews quicker than in viewDidLoad

Right now I'm allocating and initializing three UIImageViews that take up the entire screen and are stacked in the viewDidLoad method. Its actually taking some time to do this. Is there a way to do this automatically so the view just has them before its even loaded? like an init method that would speed this up?
- (void)viewDidLoad {
[super viewDidLoad];
self.mySubviews = [[NSMutableArray alloc] init];
self.videoCounterTags = [[NSMutableArray alloc] init];
int c = (int)[self.scenes count];
c--;
NSLog(#"int c = %d", c);
self.myCounter = [NSNumber numberWithInt:c];
for (int i=0; i<=c; i++) {
//create imageView
UIImageView *imageView =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
[imageView setUserInteractionEnabled:YES]; // <--- This is very important
imageView.tag = i; // <--- Add tag to track this subview in the view stack
[self.view addSubview:imageView];
NSLog(#"added image view %d", i);
//get scene object
PFObject *sceneObject = self.scenes[i];
//get the PFFile and filetype
PFFile *file = [sceneObject objectForKey:#"file"];
NSString *fileType = [sceneObject objectForKey:#"fileType"];
//check the filetype
if ([fileType isEqual: #"image"])
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
//get image
NSURL *imageFileUrl = [[NSURL alloc] initWithString:file.url];
NSData *imageData = [NSData dataWithContentsOfURL:imageFileUrl];
dispatch_async(dispatch_get_main_queue(), ^{
imageView.image = [UIImage imageWithData:imageData];
});
});
}
//its a video
else
{
// the video player
NSURL *fileUrl = [NSURL URLWithString:file.url];
self.avPlayer = [AVPlayer playerWithURL:fileUrl];
self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
//self.avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:[self.avPlayer currentItem]];
CGRect screenRect = [[UIScreen mainScreen] bounds];
self.avPlayerLayer.frame = CGRectMake(0, 0, screenRect.size.width, screenRect.size.height);
[imageView.layer addSublayer:self.avPlayerLayer];
NSNumber *tag = [NSNumber numberWithInt:i+1];
NSLog(#"tag = %#", tag);
[self.videoCounterTags addObject:tag];
}
}
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(viewTapped:)];
// dummyScreen is just a see through view that sits on top of my image stack and holds my tap gesture recognizer
[self.view bringSubviewToFront:self.dummyScreen];
[self.dummyScreen addGestureRecognizer:tapGesture];
}
The problem is this line:
dispatch_async(dispatch_get_global_queue...
That moves you onto a background thread, and thus there is no telling when the code will be executed. Hence the delay.
If these are local files (i.e., the URL is the file URL of an image file in your app bundle), there is no need for any dispatch_async in your code. Remove all of that and do everything on the main thread. That way, it will happen as fast as possible.
If these are remote files (i.e., you have to do networking to get hold of them), then there's probably nothing you can do to speed things up; networking takes time, and viewDidLoad is just about as early as you can possibly be notified that it's time to get hold of the images.

Parsing data with hpple then displaying in labels

So far I have this:
I am trying to parse date with hpple from a webpage and then display it in labels. I don't know how to go about this. I guess I have to make the Secret variable in the void GoToSecretsList somehow equal the values the other void is getting... does anyone have any suggestions?
- (void)GoToSecretsList
{
UIViewController *vc;
vc = [self.storyboard instantiateViewControllerWithIdentifier:#"SecretsListID"];
[self.navigationController pushViewController:vc animated:YES];
UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 120, 500, 40)];
[myLabel setBackgroundColor:[UIColor clearColor]];
NSString *Secret;
Secret = #"Get value from website";
[myLabel setText:[NSString stringWithFormat:#"#1: %#", Secret]];
[[vc view] addSubview:myLabel];
}
-(void)LoadSecrets {
// 1
NSURL *SecretsUrl = [NSURL URLWithString:#"http:/removed.com/xlxlx"];
NSData *SecretsHtmlData = [NSData dataWithContentsOfURL:SecretsUrl];
// 2
TFHpple *secretsParser = [TFHpple hppleWithHTMLData:SecretsHtmlData];
// 3
NSString *secretsXpathQueryString = #"/secret";
NSArray *secretsNodes = [secretsParser searchWithXPathQuery:secretsXpathQueryString];
// 4
NSMutableArray *newSecrets = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in secretsNodes) {
// 5
VOI *secret = [[VOI alloc] init];
[newSecrets addObject:secret];
// 6
secret.title = [[element firstChild] content];
// 7
secret.url = [element objectForKey:#"href"];
}
}
Edit: Now I just have this:
- (void)GoToSecretsList
{
UIViewController *vc;
vc = [self.storyboard instantiateViewControllerWithIdentifier:#"SecretsListID"];
[self.navigationController pushViewController:vc animated:YES];
UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 120, 500, 40)];
[myLabel setBackgroundColor:[UIColor clearColor]];
NSURL *SecretsUrl = [NSURL URLWithString:#"http://removed.com/dsdsds"];
NSData *SecretsHtmlData = [NSData dataWithContentsOfURL:SecretsUrl];
TFHpple *secretsParser = [TFHpple hppleWithHTMLData:SecretsHtmlData];
NSString *secretsXpathQueryString = #"/secret";
NSArray *secretsNodes = [secretsParser searchWithXPathQuery:secretsXpathQueryString];
[myLabel setText:[NSString stringWithFormat:#"#1: %#", secretsNodes]];
[[vc view] addSubview:myLabel];
}
But what variable has the information..? or what I am doing wrong? Because secretNodes isn't it.
Can you post some real html to help know what text you're looking for?
e.g. the following will get all the <h2></h2> nodes:
NSString *secretsXpathQueryString = #"//h2";//note double slashes for tag name
whereas this will get those with a specific class:
NSString *secretsXpathQueryString = #"//h2[#class='secret']";//note single quotes
Once you have the correct query, take a look at TFHppleElement.h to see which properties you might investigate, for example:
element.firstChild.content

EXC_BAD_ACCESS (CODE=2 ,ADDRESS=0Xbf7fff2c) when switching tab ios6

My code is working fine for iOS 7 but crashes in iOS 6. My app is working fine but the problem occurs when i click on a tab else its working fine.
Checked the link :EXC_BAD_ACCESS While switching tabControllers but no luck.
Below is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.webView = [[UIWebView alloc] init];
self.view.backgroundColor = [UIColor colorWithPatternImage:[JLTBackgroundHelper getBackgroundImageForView]];
self.webView.opaque = NO;
self.webView.backgroundColor = [UIColor clearColor];
UIViewController *rootVC = [[UIViewController alloc] init];
rootVC.title = #"Contact JLT Sport";
rootVC.view = self.webView;
self.viewControllers = #[rootVC];
NSString *fileName;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
// iPad-specific
fileName = #"contact_ipad";
} else {
// iPhone-specific
fileName = #"contact";
}
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:fileName ofType:#"html" inDirectory:#"Assets/web"];
NSURL *url = [NSURL fileURLWithPath:htmlFile];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
[_webView loadRequest:request];
_webView.delegate= self;
}
//send external URL requests to Safari
- (BOOL) webView:(UIWebView*)wv shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navType
{
if (navType == UIWebViewNavigationTypeLinkClicked
&& [request.URL.scheme hasPrefix:#"http"])
{
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
}
return YES;
}
#end
Plese guide/suggest.
try this :
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.webView = [[UIWebView alloc] init];
self.view.backgroundColor = [UIColor colorWithPatternImage:[JLTBackgroundHelper getBackgroundImageForView]];
self.webView.opaque = NO;
self.webView.backgroundColor = [UIColor clearColor];
UIViewController *rootVC = [[UIViewController alloc] init];
rootVC.title = #"Contact JLT Sport";
rootVC.view = self.webView;
self.viewControllers = #[rootVC];
NSString *fileName;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
// iPad-specific
fileName = #"contact_ipad";
} else {
// iPhone-specific
fileName = #"contact";
}
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:fileName ofType:#"html" inDirectory:#"Assets/web"];
NSURL *url = [NSURL fileURLWithPath:htmlFile];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
self.webView.delegate= self;
}
if above solution does not work then try this:
Debug with Instrument
Go to Product >> Profile >> All > Zoombies
Press "Record" button on top left corner
Perform your task and when application get EXC_BAD_ACCESS the instrument give that line where the application was being crash.
Also debug in this method to:[JLTBackgroundHelper getBackgroundImageForView];
**Make sure that all variable is being get memory before use it.**
May be the resin is that some method is depreciated in iOS 7.
These are the possible scenario of application is being crash and its solution.

Rendering the layer of a UIWebView that contains an SVG file

I am attempting to use this method I've constructed to save the layer of a UIWebView as an image. That is working but the SVG I have loaded into the UIView is not getting rendered in the image, only the background of the UIWebView.
+ (BOOL)imageFromSVGinWebView:(UIView *)theView usePNG:(BOOL)usePNG; {
UIGraphicsBeginImageContext(theView.frame.size);
[theView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *layerImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *layerIMGData = nil;
NSString *pathComponent = nil;
if (usePNG) {
layerIMGData = UIImagePNGRepresentation(layerImage);
pathComponent = #"png";
}else {
layerIMGData = UIImageJPEGRepresentation(layerImage,1.0f);
pathComponent = #"jpg";
}
NSString *appFile = [[CCFileManagement conversionsDirectory] stringByAppendingPathComponent:String(#"img.%#",pathComponent)];
NSError *error = nil;
BOOL returnBOOL = [layerIMGData writeToFile:appFile options:NSDataWritingAtomic error:&error];
if(error != nil)
ILogPlus(#"%#",error);
return returnBOOL;
}
In summary, I've loaded an SVG into a UIWebView, saved that UIWebView as an image, opened the image and the image does not have the SVG in it. I have done this with other views successfully, something is different about the SVG or UIWebView.
UPDATE:
If I add a delay to make the app wait a few seconds to execute the image saving code then it works. Putting that code in webViewDidFinishLoad does NOT work. Obviously webViewDidFinishLoad doesn't count SVGs.
I have found that if you add a .1 second delay it will work
- (void)webViewDidFinishLoad:(UIWebView *)webView; {
[self performSelector:#selector(postLoadActions:) withObject:webView afterDelay:0.1f];
}
- (void)postLoadActions:(UIWebView *)webView; {
if (![CCConversion imageFromSVGinWebView:webView usePNG:YES]) {
ILogPlus(#"Didn't work");
}
NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[CCFileManagement conversionsDirectory] error:NULL];
ILogPlus(#"%#",array);
//[webView removeFromSuperview];
[webView release];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:[[CCFileManagement conversionsDirectory] stringByAppendingPathComponent:#"img.png"]]];
imageView.frame = CGRectMake(90, 90, imageView.frame.size.width, imageView.frame.size.height);
imageView.backgroundColor = [UIColor clearColor];
[self.view performSelector:#selector(addSubview:) withObject:imageView afterDelay:2.0f];
[imageView release];
}

Resources