Trouble hiding iAd banner and displaying UIWebView in its place - ios

When there is no iAd banner to display, we would like to display a UIWebView of the same dimensions pointed to a specific URL.
However, hiding the iAd banner and showing the UIWebView doesn't work. We embed the show/hide code inside bannerViewDidLoadAd and didFailToReceiveAdWithError. All that appears is the white, blank rectangle when there is no iAd inventory instead of our UIWebView.
If a user clicks on a link inside the UIWebView, we would like the link to open in Safari. Do we need to add a delegate to the UIWebView?
Code:
//
// SAiOSAdPlugin.m
// Ad Plugin for PhoneGap
//
// Created by shazron on 10-07-12.
// Copyright 2010 Shazron Abdullah. All rights reserved.
// Cordova v1.5.0 Support added 2012 #RandyMcMillan
//
#import "SAiOSAdPlugin.h"
//#ifdef CORDOVA_FRAMEWORK
#import <Cordova/CDVDebug.h>
//#else
//#import "CDVDebug.h"
//#endif
#interface SAiOSAdPlugin(PrivateMethods)
- (void) __prepare:(BOOL)atBottom;
- (void) __showAd:(BOOL)show;
#end
#implementation SAiOSAdPlugin
#synthesize adView;
#synthesize bannerIsVisible, bannerIsInitialized, bannerIsAtBottom, isLandscape;
#pragma mark -
#pragma mark Public Methods
- (void) resizeViews
{
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass && self.adView)
{
CGRect webViewFrame = [super webView].frame;
CGRect superViewFrame = [[super webView] superview].frame;
CGRect adViewFrame = self.adView.frame;
BOOL adIsShowing = [[[super webView] superview].subviews containsObject:self.adView];
if (adIsShowing)
{
if (self.bannerIsAtBottom) {
webViewFrame.origin.y = 0;
CGRect adViewFrame = self.adView.frame;
CGRect superViewFrame = [[super webView] superview].frame;
adViewFrame.origin.y = (self.isLandscape ? superViewFrame.size.width : superViewFrame.size.height) - adViewFrame.size.height;
self.adView.frame = adViewFrame;
} else {
webViewFrame.origin.y = adViewFrame.size.height;
}
webViewFrame.size.height = self.isLandscape? (superViewFrame.size.width - adViewFrame.size.height) : (superViewFrame.size.height - adViewFrame.size.height);
}
else
{
webViewFrame.size = self.isLandscape? CGSizeMake(superViewFrame.size.height, superViewFrame.size.width) : superViewFrame.size;
webViewFrame.origin = CGPointZero;
}
[UIView beginAnimations:#"blah" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[super webView].frame = webViewFrame;
[UIView commitAnimations];
}
}
- (void) orientationChanged:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
{
NSInteger orientation = [[arguments objectAtIndex:0] integerValue];
switch (orientation) {
// landscape
case 90:
case -90:
self.isLandscape = YES;
break;
// portrait
case 0:
case 180:
self.isLandscape = NO;
break;
default:
break;
}
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass && self.adView)
{
self.adView.currentContentSizeIdentifier = self.isLandscape ? ADBannerContentSizeIdentifierLandscape : ADBannerContentSizeIdentifierPortrait;
[self resizeViews];
}
}
- (void) prepare:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
NSUInteger argc = [arguments count];
if (argc > 1) {
return;
}
NSString* atBottomValue = [arguments objectAtIndex:0];
[self __prepare:[atBottomValue boolValue]];
}
- (void) showAd:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
NSUInteger argc = [arguments count];
if (argc > 1) {
return;
}
NSString* showValue = [arguments objectAtIndex:0];
[self __showAd:[showValue boolValue]];
}
#pragma mark -
#pragma mark Private Methods
- (void) __prepare:(BOOL)atBottom
{
NSLog(#"SAiOSAdPlugin Prepare Ad At Bottom: %d", atBottom);
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass && !self.adView)
{
self.adView = [[ADBannerView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
// we are still using these constants even though they are deprecated - if it is changed, iOS 4 devices < 4.3 will crash.
// will need to do a run-time iOS version check
self.adView.requiredContentSizeIdentifiers = [NSSet setWithObjects: ADBannerContentSizeIdentifierPortrait, ADBannerContentSizeIdentifierLandscape, nil];
self.adView.delegate = self;
NSString* contentSizeId = (self.isLandscape ? ADBannerContentSizeIdentifierLandscape : ADBannerContentSizeIdentifierPortrait);
self.adView.currentContentSizeIdentifier = contentSizeId;
if (atBottom) {
self.bannerIsAtBottom = YES;
}
self.bannerIsVisible = NO;
self.bannerIsInitialized = YES;
self.houseAdView = [[UIWebView alloc] initWithFrame: CGRectMake(0.0, 0.0, 1.0, 1.0)];
self.houseAdView.frame = self.adView.frame;
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://www.panabee.com"]];
[self.houseAdView loadRequest: request];
}
}
- (void) __showAd:(BOOL)show
{
NSLog(#"SAiOSAdPlugin Show Ad: %d", show);
if (!self.bannerIsInitialized){
[self __prepare:NO];
}
if (!(NSClassFromString(#"ADBannerView") && self.adView)) { // ad classes not available
return;
}
if (show == self.bannerIsVisible) { // same state, nothing to do
return;
}
if (show)
{
[UIView beginAnimations:#"blah" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[[[super webView] superview] addSubview:self.adView];
[[[super webView] superview] bringSubviewToFront:self.houseAdView];
[[[super webView] superview] bringSubviewToFront:self.adView];
[self resizeViews];
[UIView commitAnimations];
self.bannerIsVisible = YES;
}
else
{
[UIView beginAnimations:#"blah" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[self.adView removeFromSuperview];
[self resizeViews];
[UIView commitAnimations];
self.bannerIsVisible = NO;
}
}
#pragma mark -
#pragma ADBannerViewDelegate
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass)
{
NSString* jsString =
#"(function(){"
"var e = document.createEvent('Events');"
"e.initEvent('iAdBannerViewDidLoadAdEvent');"
"document.dispatchEvent(e);"
"})();";
[banner setHidden:YES];
[self.houseAdView setHidden:NO];
[super writeJavascript:[NSString stringWithFormat:jsString]];
}
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError*)error
{
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass)
{
NSString* jsString =
#"(function(){"
"var e = document.createEvent('Events');"
"e.initEvent('iAdBannerViewDidFailToReceiveAdWithErrorEvent');"
"e.error = '%#';"
"document.dispatchEvent(e);"
"})();";
[banner setHidden:YES];
[self.houseAdView setHidden:NO];
[super writeJavascript:[NSString stringWithFormat:jsString, [error description]]];
}
}
#end

It's me again :)
You're not adding it to the sub view tree.
From your __prepare method
self.houseAdView = [[UIWebView alloc] initWithFrame: CGRectMake(0.0, 0.0, 1.0, 1.0)];
self.houseAdView.frame = self.adView.frame;
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://www.panabee.com"]];
[self.houseAdView loadRequest: request];
That's great. But it doesn't work - you are missing one line of code - a critical, vital line that gets every developer some time or another.
[self addSubview:self.houseAdView];
I'm making a few assumptions, like that self is a UIView. Test before shipping.
So, that part of your __prepare method should look like this:
self.houseAdView = [[UIWebView alloc] initWithFrame: CGRectMake(0.0, 0.0, 1.0, 1.0)];
self.houseAdView.frame = self.adView.frame;
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://www.panabee.com"]];
[self.houseAdView loadRequest: request];
[self addSubview:self.houseAdView];

Related

iOS - My app crashes with memory Error if only runs on Device

My app runs perfectly on simulator.
But when I run it on device to test, the app crashed.
The displayed error :
"malloc: * error for object 0x17415d0c0: Invalid pointer dequeued from free list * set a breakpoint in malloc_error_break to debug";
And another error sometimes happens :
"Thread 6 com.apple.NSURLConnectionLoader: Program received signal: EXC_BAD_ACCESS"
This two errors are random, it happens after the app runs two or three minutes.
I searched Google and find some solution.
It says that set a breakpoint in malloc_error_break to debug, but this only work on simulator. Even I set the malloc_error_break, the app still crush and it does not display anything, I only can see that error message.
This is big project, I really do not know which part of the code cause the problem and which part of the code I need to post.
But I have doubt with one of the class, my 'SynchroningView'.
This view will be displayed if only my app make synchronisation with the server. It means this view is included in almost all the Viewcontroller in my project.
Here is my 'SynchroningView' class:
"SynchroningView.h"
#import <UIKit/UIKit.h>
#class SynchroningView;
#protocol SynchroningViewDelegate
#optional
- (void)SynchroningViewCancelButtonDidClicked:(SynchroningView *)synchroningView;
- (void)SynchroningViewStartTherapyButtonDidClicked:(SynchroningView *)synchroningView;
#end
#interface SynchroningView : UIView <DataManagerDelegate>
#property (nonatomic, assign) id<SynchroningViewDelegate>delegateCustom;
#property (nonatomic, retain) UIButton *containerButton;
#property (nonatomic, retain) Patient *singlePatient;
- (instancetype)initWithFrame:(CGRect)frame;
- (void)showInView:(UIView *)view;
- (void)dismissMenuPopover;
#end
SynchroningView.m
#import "SDDemoItemView.h"
#import "SDPieLoopProgressView.h"
#define Directory_Document [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
#define FileName_Image_SynchroningView_BackGroundImageName #"SynchroningView_BackGroundImage"
#define FilePath_Image_SynchroningView_BackGroundImageName [Directory_Document stringByAppendingPathComponent:FileName_Image_SynchroningView_BackGroundImageName]
#interface SynchroningView ()
#property (nonatomic, strong) DataManager* dataManager;
#property (nonatomic, retain) UILabel* messageLabel;
#property (nonatomic, retain) UIButton* CancelButton;
#property (nonatomic, retain) CoolButton* ConfirmButton;
#property (nonatomic, retain) CoolButton* startTherapyButton;
#property (nonatomic, strong) SDDemoItemView* demoProgressView;
#end
#interface SynchroningView ()
{
BOOL _blinking;
NSTimer *timer;
}
#end
#implementation SynchroningView
-(void)dealloc
{
}
//get the background Image, make it blur and save it. In this way I do not have to use Blur function everytim, I use the blured image directly
- (UIImage *)getBackGroundImage
{
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:FilePath_Image_SynchroningView_BackGroundImageName]) {
return [UIImage imageWithContentsOfFile:FilePath_Image_SynchroningView_BackGroundImageName];
}
else{
UIImage *backImage = [UIImage imageWithContentsOfFile:kBackgroundImagePath];
backImage = [backImage blurWithFloat:20.0f];
NSData * binaryImageData = UIImagePNGRepresentation(backImage);
if ([binaryImageData writeToFile:FilePath_Image_SynchroningView_BackGroundImageName atomically:YES]) {
return backImage;
}
}
return [UIImage imageWithContentsOfFile:kBackgroundImagePath];
}
-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_blinking = NO;
self.dataManager = [[DataManager alloc] init];
self.dataManager.DelegateCustom = self;
self.backgroundColor = [UIColor clearColor];
self.containerButton = [[UIButton alloc] init];
[self.containerButton setBackgroundColor:RGBA_Custom(0, 0, 0, 0.6f)];
[self.containerButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin];
UIView *shadowView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
[self addSubview:shadowView];
shadowView.backgroundColor = RGBA_Custom(230, 249, 251, 0.96f);
// shadowView.layer.borderWidth = 2*IPAD;
// shadowView.layer.borderColor = [RGBA_Custom(199, 199, 199, 1.0f) CGColor];
shadowView.layer.shadowColor = [UIColor blackColor].CGColor;
shadowView.layer.shadowOpacity = 0.4;
shadowView.layer.shadowRadius = 4*IPAD;
shadowView.layer.shadowOffset = CGSizeMake(4.0f*IPAD, 4.0f*IPAD);
shadowView.layer.cornerRadius = 6*IPAD;
shadowView.userInteractionEnabled = NO;
UIImageView *backGround = [[UIImageView alloc] initWithImage:[self getBackGroundImage]];
backGround.frame = CGRectMake(0, 0, shadowView.frame.size.width, shadowView.frame.size.height);
backGround.backgroundColor = [UIColor clearColor];
[shadowView addSubview:backGround];
backGround.layer.cornerRadius = shadowView.layer.cornerRadius;
backGround.layer.masksToBounds = YES;
ImageWIDTH_ = self.frame.size.height*0.3;
self.demoProgressView =[SDDemoItemView demoItemViewWithClass:[SDPieLoopProgressView class]];
self.demoProgressView.frame = CGRectMake((self.frame.size.width - ImageWIDTH_)/2,
kFromLeft,
ImageWIDTH_,
ImageWIDTH_);
[self addSubview:self.demoProgressView];
self.messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(kFromLeft,
self.demoProgressView.frame.origin.y + self.demoProgressView.frame.size.height + kFromLeft,
self.frame.size.width - kFromLeft*2,
self.frame.size.height - (self.demoProgressView.frame.origin.y + self.demoProgressView.frame.size.height + kFromLeft*2))];
self.messageLabel.backgroundColor = [UIColor clearColor];
self.messageLabel.textColor = [UIColor blackColor];
self.messageLabel.textAlignment = NSTextAlignmentCenter;
self.messageLabel.numberOfLines = 0;
self.messageLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.messageLabel.font = [UIFont boldSystemFontOfSize:kIPAD ? 20:12];
self.messageLabel.text = #"";
self.messageLabel.adjustsFontSizeToFitWidth = YES;
[self addSubview:self.messageLabel];
CGFloat BtnHeight = kIPAD ? 40 : 30;
self.CancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.CancelButton.frame = CGRectMake(self.frame.size.width - kFromLeft*0.5 - BtnHeight,
kFromLeft*0.5,
BtnHeight,
BtnHeight);
self.CancelButton.backgroundColor = [UIColor clearColor];
[self.CancelButton setImage:[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"utilities_close" ofType:#"png"]] forState:UIControlStateNormal];
[self.CancelButton addTarget:self action:#selector(pressCancelButton:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.CancelButton];
BtnHeight = kIPAD ? 70 : 50;
CGFloat BtnWidth = self.frame.size.width/4;
NSString* ConfirmButtonStr = NSLocalizedString(#"Confirm", nil);
ExpectedSize = [ConfirmButtonStr sizeWithFont:self.messageLabel.font constrainedToSize:CGSizeMake(VIEW_WIDTH, BtnHeight) lineBreakMode:NSLineBreakByWordWrapping];
ExpectedSize = CGSizeMake(ExpectedSize.width + 30*IPAD, ExpectedSize.height);
self.ConfirmButton = [CoolButton buttonWithType:UIButtonTypeCustom];
self.ConfirmButton.frame = CGRectMake((self.frame.size.width - ExpectedSize.width)/2,
self.frame.size.height - BtnHeight - kFromLeft,
ExpectedSize.width,
BtnHeight);
self.ConfirmButton.titleLabel.font = self.messageLabel.font;
[self.ConfirmButton setTitle:ConfirmButtonStr forState:UIControlStateNormal];
[self.ConfirmButton addTarget:self action:#selector(pressConfirmButton:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.ConfirmButton];
BtnWidth = self.frame.size.width*0.6;
NSString* startTherapyButtonStr = NSLocalizedString(#"StartTerapia", nil);
ExpectedSize = [startTherapyButtonStr sizeWithFont:self.messageLabel.font constrainedToSize:CGSizeMake(VIEW_WIDTH, BtnHeight) lineBreakMode:NSLineBreakByWordWrapping];
ExpectedSize = CGSizeMake(ExpectedSize.width + 30*IPAD, ExpectedSize.height);
self.startTherapyButton = [CoolButton buttonWithType:UIButtonTypeCustom];
self.startTherapyButton.frame = CGRectMake((self.frame.size.width - ExpectedSize.width)/2,
self.ConfirmButton.frame.origin.y,
ExpectedSize.width,
self.ConfirmButton.frame.size.height);
self.startTherapyButton.titleLabel.font = self.messageLabel.font;
[self.startTherapyButton setTitle:startTherapyButtonStr forState:UIControlStateNormal];
[self.startTherapyButton addTarget:self action:#selector(startTherapyButtonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.startTherapyButton];
self.CancelButton.alpha = 0.0;
self.ConfirmButton.alpha = 0.0;
self.startTherapyButton.alpha = 0.0;
if (self.dataManager.firstSynchronizationAgain == 1 && [AccessedInfo getAccessedInfo]) {
UILabel *alertInfoLabel = [[UILabel alloc] initWithFrame:CGRectMake(kFromLeft,
0,
self.frame.size.width - kFromLeft*2,
VIEW_HEIGHT)];
alertInfoLabel.backgroundColor = [UIColor clearColor];
alertInfoLabel.textColor = COLOR_CIRCLE;
alertInfoLabel.textAlignment = NSTextAlignmentCenter;
alertInfoLabel.numberOfLines = 0;
alertInfoLabel.lineBreakMode = NSLineBreakByWordWrapping;
alertInfoLabel.font = [UIFont systemFontOfSize:self.startTherapyButton.titleLabel.font.pointSize-2];
alertInfoLabel.text = NSLocalizedString(#"SynchronizingNew", nil);
ExpectedSize = [alertInfoLabel.text sizeWithFont:alertInfoLabel.font constrainedToSize:alertInfoLabel.frame.size lineBreakMode:NSLineBreakByWordWrapping];
alertInfoLabel.frame = CGRectMake(alertInfoLabel.frame.origin.x,
self.startTherapyButton.frame.origin.y - ExpectedSize.height - IPAD*2,
alertInfoLabel.frame.size.width,
ExpectedSize.height);
[self addSubview:alertInfoLabel];
}
[self.containerButton addSubview:self];
}
return self;
}
//show the synchronization result message
- (void)setMessageLabelString:(NSString *)labelName
{
self.messageLabel.text = labelName;
ExpectedSize = [labelName sizeWithFont:self.messageLabel.font constrainedToSize:CGSizeMake(self.messageLabel.frame.size.width, VIEW_HEIGHT) lineBreakMode:NSLineBreakByWordWrapping];
self.messageLabel.frame = CGRectMake(self.messageLabel.frame.origin.x,
self.messageLabel.frame.origin.y,
self.messageLabel.frame.size.width,
ExpectedSize.height);
timer = [NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:#selector(MessageLabelBlinking) userInfo:nil repeats:YES];
// self.messageLabel.adjustsFontSizeToFitWidth = YES;
}
- (void)MessageLabelBlinking
{
if (_blinking) {
NSString *threeDot = #".....";
if ([self.messageLabel.text rangeOfString:threeDot].location == NSNotFound) {
self.messageLabel.text = [self.messageLabel.text stringByAppendingString:#"."];
}
else{
self.messageLabel.text = [self.messageLabel.text stringByReplacingOccurrencesOfString:threeDot withString:#""];
}
}
else{
[timer invalidate];
timer = nil;
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
//init the data processing block
- (void)initCustomOtherParameters
{
self.dataManager.DelegateCustom = self;
self.dataManager.blockProcessingData = ^(float allCommand, float restCommand){
if (allCommand == 0) {
[[SingletonOperationQueue mainQueue] addOperationWithBlock:^{
self.demoProgressView.progressView.progress = 1;
NSString *messageStr = [NSLocalizedString(#"SuccessfulSynchronized", nil) stringByAppendingFormat:#"\n%#", NSLocalizedString(#"EmptyTherapy", nil)];
[self setMessageLabelString:messageStr];
_blinking = NO;
self.CancelButton.alpha = 1.0;
}];
}
else{
float percenAger = (restCommand/allCommand);
percenAger = 1 - percenAger;
[[SingletonOperationQueue mainQueue] addOperationWithBlock:^{
self.demoProgressView.progressView.progress = percenAger;
if (restCommand == 0) {
[self downloadZipFile];
}
}];
}
};
[Patient RemovePatient];
[self.singlePatient SavePatient];
}
- (void)showInView:(UIView *)view
{
self.transform = CGAffineTransformScale(self.transform, 0.8, 0.8);
self.containerButton.alpha = 0.0f;
self.containerButton.frame = view.bounds;
[view addSubview:self.containerButton];
[UIView animateWithDuration:0.15 animations:^{
self.containerButton.alpha = 1.0f;
self.transform = CGAffineTransformScale(self.transform, 1.4, 1.4);
}completion:^(BOOL finished) {
if (finished) {
[UIView animateWithDuration:0.20 animations:^{
self.transform = CGAffineTransformIdentity;
}];
[self sendConnectionTestRequest];
}
else{
self.transform = CGAffineTransformIdentity;
[self sendConnectionTestRequest];
}
}];
}
- (void)dismissMenuPopover
{
[self hide];
}
- (void)hide
{
[UIView animateWithDuration:0.25 animations:^{
self.transform = CGAffineTransformScale(self.transform, 0.8, 0.8);
self.containerButton.alpha = 0.0f;
}completion:^(BOOL finished) {
if (finished) {
[self.containerButton removeFromSuperview];
}
}];
}
- (void)pressCancelButton:(UIButton *)button
{
[self.dataManager CommunicationCancel];
[self.delegateCustom SynchroningViewCancelButtonDidClicked:self];
}
- (void)startTherapyButtonDidClicked:(UIButton *)button
{
[self.delegateCustom SynchroningViewStartTherapyButtonDidClicked:self];
}
- (void)pressConfirmButton:(UIButton *)button
{
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 0.0;
self.ConfirmButton.alpha = 0.0;
}];
[self sendRegistrationRequestConfirm:YES];
}
#pragma mark - Communication
- (void)sendConnectionTestRequest
{
[self initCustomOtherParameters];
_blinking = YES;
[self setMessageLabelString:NSLocalizedString(#"StartRegistration", nil)];
[self.dataManager sendRequestCommand:kConnectionTest];
}
- (void)sendRegistrationRequestConfirm:(BOOL)Confirm
{
[self setMessageLabelString:NSLocalizedString(#"StartRegistration", nil)];
NSString *registrationResult = [self.dataManager RegisterTheUSER_Confirm:Confirm];
[self processLogInResult:registrationResult];
}
- (void)processLogInResult:(NSString *)logInResult
{
if ([logInResult isEqual:#"1"]) {
if ([self.dataManager DataInitialization]) {
[self.dataManager DataInitializationForFakeUser];
[self.singlePatient SavePatient];
[self startTherapyButtonDidClicked:nil];
}
}
else if ([logInResult isEqual:#"2"]) {
if ([self.dataManager DataInitialization]) {
self.singlePatient.record7_AuthenticatedUser = YES;
[self.singlePatient SavePatient];
[self.dataManager sendRequestCommand:kNewDataAvailable];
};
}
else if ([logInResult intValue] == DEVICE_NOT_REGISTERED){
logInResult = NSLocalizedString(#"105", nil);
_blinking = NO;
[self setMessageLabelString:logInResult];
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
self.ConfirmButton.alpha = 1.0;
}];
}
else if ([logInResult isEqualToString:kNO]){
_blinking = NO;
[self setMessageLabelString:#"Cannot find the Error "];
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
}];
}
else{
_blinking = NO;
[self setMessageLabelString:logInResult];
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
}];
}
}
- (void)downloadZipFile
{
self.demoProgressView.progressView.progress = 1.0;
sleep(0.4);
[self setMessageLabelString:NSLocalizedString(#"Loading Data", nil)];
self.demoProgressView.progressView.progress = 0.0;
self.dataManager.blockProcessingDataPercentAge = ^(float percentAge, NSString *fileName){
if ([fileName isEqualToString:kaderenzainfo]) {
[[SingletonOperationQueue mainQueue] addOperationWithBlock:^{
self.demoProgressView.progressView.progress = percentAge;
NSLog(#"%f", percentAge);
if (percentAge == 0.5) {
sleep(0.4);
NSString *aderenzainfoFilePath = [[NSUserDefaults standardUserDefaults] objectForKey:kaccertamentiinfo];
[self.dataManager downloadZipFile:aderenzainfoFilePath fileName:kaccertamentiinfo];
}
}];
}
else if ([fileName isEqualToString:kaccertamentiinfo]){
[[SingletonOperationQueue mainQueue] addOperationWithBlock:^{
self.demoProgressView.progressView.progress = 0.5 + percentAge;
if (0.5 + percentAge >= 1.0) {
_blinking = NO;
self.CancelButton.alpha = 1.0;
if ([Patient getPatient].record_patientStatus == PatientStatusSuspendedType) {
[self setMessageLabelString:NSLocalizedString(#"SuspendedPatient", nil)];
}
else if ([Patient getPatient].record_patientStatus == PatientStatusDeletedType){
[self setMessageLabelString:NSLocalizedString(#"DeletedPatient", nil)];
}
else if ([Patient getPatient].record_patientStatus == PatientStatusActiveType){
[self setMessageLabelString:NSLocalizedString(#"SuccessfulSynchronized", nil)];
self.startTherapyButton.alpha = 1.0;
}
}
}];
}
};
NSString *aderenzainfoFilePath = [[NSUserDefaults standardUserDefaults] objectForKey:kaderenzainfo];
[self.dataManager downloadZipFile:aderenzainfoFilePath fileName:kaderenzainfo];
}
#pragma mark - DataManagerDelegate
- (void)CommunicationConnectionTest:(BOOL)connected
{
if (connected) {
[self sendRegistrationRequestConfirm:NO];
}
else{
[self setMessageLabelString:NSLocalizedString(#"connectionTestFail", nil)];
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
}];
_blinking = NO;
}
}
- (void)CommunicationSendRequestCommandName:(NSString *)commandName
{
if ([commandName isEqualToString:kNewDataAvailable]) {
[self setMessageLabelString:NSLocalizedString(#"Synchronizing", nil)];
}
}
- (void)CommunicationReceiveResponseWithOKCommandName:(NSString *)commandName
{
}
- (void)CommunicationReceiveResponseWithRequestError:(NSString *)commandName
{
[self setMessageLabelString:NSLocalizedString(#"NetworkConnectionError", nil)];
_blinking = NO;
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
}];
}
- (void)CommunicationReceiveResponseCommandName:(NSString *)commandName WithErrorCode:(int)errorCode withErrorDescription:(NSString *)errorDescription
{
[self setMessageLabelString:NSLocalizedString(#"NewDataAvaiableErrorCode", nil)];
_blinking = NO;
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
}];
}
-(void)CommunicationZipFileFailDownload
{
[self setMessageLabelString:NSLocalizedString(#"ZipFileDownloadFail", nil)];
_blinking = NO;
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
}];
}
-(void)CommunicationZipFileIsNotReadAble
{
[self setMessageLabelString:NSLocalizedString(#"ZipFileUnzippedFail", nil)];
_blinking = NO;
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
}];
}
#end
I solved it finally
Inside my Encryption and Decryption function, I have this:
Byte *buffer = (Byte*)malloc(asciiDataLength);
After I processed with buffer, I convert it to NSData:
NSData *plainData = [NSData dataWithBytesNoCopy:buffer length:asciiDataLength freeWhenDone:YES];
This code causes my app crushes continuously, I changed it to
NSData *plainData = [NSData dataWithBytes:buffer length:asciiDataLength];
free(buffer);
Then my app never crush again.
So, I have to free the Byte by myself, ARC will not free it for me.
Simulator's memory = Pc's RAM i.e 4 or 6 gb etc.
and device have only 1 gb maximum. In Xcode while you run the app, you need to click on Debug Navigator, and then click on Memory, it will display the memory consumption of your app.
To see the Leakage of Memory in your code - you have to go to memory tools, like Instruments.

Fade Effect when Scrolling

I would like to add the fade effect when user scroll my galleryViewController which fetch the data from the server. I could not able to implement the fade effect to my scrollViewController.
Code:
#import "GrillGalleryCollectionViewController.h"
#import "AFNetworking.h"
#interface GrillGalleryCollectionViewController ()
#end
#implementation GrillGalleryCollectionViewController
#synthesize scrollView,pageControl, colors;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// colors=[[NSArray alloc]init];
colors = [[NSArray alloc] init];;
[self getActiveOffers];
// NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil];
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// Update the page when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)changePage:(id)sender {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
[self.scrollView scrollRectToVisible:frame animated:YES];
}
- (IBAction)backBtnPressed:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
}
- (void) getActiveOffers {
NSString *string = #"http://znadesign.com/appcenter/api.php?function=get_gallery&customer_id=1";
NSLog(#"%#", string);
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
int total_count = (int)[[responseObject valueForKey:#"total_count"] integerValue];
if (total_count > 0) {
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:total_count];
for (int i = 1; i <= total_count; i++) {
NSString *key = [NSString stringWithFormat:#"%i", i];
id object = [responseObject objectForKey:key];
[array addObject:object];
}
colors = [NSArray arrayWithArray:array];
[self setSizeSliding];
// [myTableView reloadData];
}
else
{
UIAlertView *alertView2 = [[UIAlertView alloc] initWithTitle:#"There is no internet connection."
message:nil
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView2 show];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"There is no internet connection."
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}
-(void) setSizeSliding
{
for (int i = 0; i < colors.count; i++) {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
// UIView *subview = [[UIView alloc] initWithFrame:frame];
// subview.backgroundColor = [colors objectAtIndex:i];
// NSString *imageURLString=[[offersArray objectAtIndex:indexPath.row] valueForKey:#"picture"];
NSString*slidingImage = [[colors objectAtIndex:i] valueForKey:#"picture"];
NSURL *url = [NSURL URLWithString:slidingImage];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *tmpImage = [[UIImage alloc] initWithData:data];
UIImageView *slidingImageView = [[UIImageView alloc]initWithFrame:frame];
slidingImageView.image = tmpImage;
[self.scrollView addSubview:slidingImageView];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * colors.count, self.scrollView.frame.size.height);
}
#end
I want to implement the similar fade effect as it is listed below:
[UIView animateWithDuration:2
animations:^{imageView.alpha = 0.0;}
completion:^(BOOL finished){ [imageView removeFromSuperview];}];
You have the code Can you adding the below code and try whether the animation works..
-(void) animateSubViews
{
int buffer = 10;
CGRect frame = CGRectMake((self.pageControl.currentPage * self.scrollView.frame.size.width)-buffer, 0, self.scrollView.frame.size.width + buffer, self.scrollView.frame.size.height);
[UIView animateWithDuration:0.4
animations:^{
for (UIView *view in self.scrollView.subviews)
{
if (CGRectContainsRect(frame, view.frame))
{
[view setAlpha:1.0];
}
else
{
[view setAlpha:0.0];
}
}
}];
}
Try calling this method from ScrollView did scroll and change page.
- (IBAction)changePage:(id)sender {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
[self.scrollView scrollRectToVisible:frame animated:YES];
//Call to animate
[self animateSubViews];
}
- (void)scrollViewDidScroll:(UIScrollView *)sender
{
// Update the page when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
//Call to animate
[self animateSubViews];
}

UITextView inside the UIImageView

I have UIImageView.If i tap the imageview it zoom in.if i CLICK or TOUCH anywhere inside the imageview i get the textview.So what happen is,if i touch bottom of Imageview,textview does not appear.Also after i touch and get the textview inside the imageview,if i touch below of the imageview it disappear the above textview.Simultaneously i want to save the data of textview content into SQLite database without using save button.I want to save all textview text in sqlite database as well as it should be in one row(in textview column-text1,text2,text3).
Below .H coding
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import <CoreLocation/CoreLocation.h>
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import <sqlite3.h>
#import "SqliteDBOne.h"
#import "LocationModel.h"
#import "BusinessModeOne.h"
#interface CameraGalleryViewController : UIViewController<UIGestureRecognizerDelegate,UIImagePickerControllerDelegate,UITextViewDelegate,CLLocationManagerDelegate,UITextFieldDelegate,UINavigationControllerDelegate>
{
SqliteDBOne *manage;
UIView *dynamicView;
UIImageView *dynamicImg;
UITextView *textview;
float xvalue;
float yvalue;
CGFloat animatedDistance;
}
.M part
#import "CameraGalleryViewController.h"
#interface CameraGalleryViewController ()
#end
#implementation CameraGalleryViewController
#synthesize cameragalleryimage,swi,textfld,locationLabel,dateLabel,timeLabel,locationManager,array_Image;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
manage =[SqliteDBOne shareOne];
//[manage createDB];
[SqliteDBOne createDBOne];
[self tapdetected1];
//DATE LABEL
NSDate* date = [NSDate date];
NSDateFormatter* formatterDate = [[NSDateFormatter alloc] init];
[formatterDate setDateFormat:#"dd-MM-yyyy"];
NSString *strDate = [formatterDate stringFromDate:date];
dateLabel.text=strDate;
//TIME LABEl
NSDate* date1 = [NSDate date];
NSDateFormatter* formatterTime = [[NSDateFormatter alloc] init];
[formatterTime setDateFormat:#"HH:mm:ss"];
NSString* strTime = [formatterTime stringFromDate:date1];
timeLabel.text=strTime;
array_Image=[[NSMutableArray alloc]init];
[self startSignificantChangeUpdates];
}
- (void)viewWillAppear:(BOOL)animated
{
UITapGestureRecognizer *tapgesture1 =[[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(tapdetected1)];
tapgesture1.numberOfTapsRequired =1;
tapgesture1.numberOfTouchesRequired =1;
cameragalleryimage.userInteractionEnabled =YES;
[cameragalleryimage addGestureRecognizer:tapgesture1];
UITapGestureRecognizer *tapgesture2 =[[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(tapdetected2)];
tapgesture2.numberOfTouchesRequired=1;
tapgesture2.numberOfTapsRequired=1;
cameragalleryimage.userInteractionEnabled =YES;
[cameragalleryimage addGestureRecognizer:tapgesture2];
UITapGestureRecognizer *tapgesture3 =[[UITapGestureRecognizer alloc]initWithTarget:self
action:#selector(tapdetected3)];
tapgesture3.numberOfTapsRequired =1;
tapgesture3.numberOfTouchesRequired =1;
cameragalleryimage.userInteractionEnabled =YES;
[cameragalleryimage addGestureRecognizer:tapgesture3];
}
-(void)tapdetected1
{
UIImagePickerController *picker =[[UIImagePickerController alloc]init];
picker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
picker.delegate =self;
[self presentViewController:picker animated:NO completion:nil];
}
-(void)tapdetected2
{
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.sourceType =UIImagePickerControllerSourceTypeCamera;
picker.delegate =self;
[self presentViewController:picker animated:NO completion:nil];
}
-(void)tapdetected3
{
//For dynamically creating view
dynamicView =[[UIView alloc]initWithFrame:CGRectMake(10, 100, 280, 260)];
dynamicView.backgroundColor=[UIColor whiteColor];
[self.view addSubview:dynamicView];
//For dynamically creating imageview
dynamicImg =[[UIImageView alloc]init];
dynamicImg.frame=CGRectMake(10, 100, 280, 260);
[dynamicImg setUserInteractionEnabled:YES];
dynamicImg.image =cameragalleryimage.image;
[dynamicView addSubview:dynamicImg];
UITapGestureRecognizer *tapgesture4 =[[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(tapdetected4)];
tapgesture4.numberOfTapsRequired=1;
tapgesture4.numberOfTouchesRequired=1;
dynamicImg.userInteractionEnabled =YES;
[dynamicImg addGestureRecognizer:tapgesture4];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch =[[event allTouches]anyObject];
CGPoint touchPoint = [touch locationInView:dynamicImg];
NSLog(#"Touch x :%f y: :%f",touchPoint.x,touchPoint.y);
xvalue =touchPoint.x;
yvalue =touchPoint.y;
}
-(void)tapdetected4
{
if (xvalue > 145.0)
{
xvalue = 145.00;
}
textview =[[UITextView alloc]initWithFrame:CGRectMake(xvalue, yvalue, 130, 40)];
[textview setDelegate:self];
[[textview layer] setBorderColor:[[UIColor grayColor] CGColor]];
[[textview layer] setBorderWidth:2.3];
[[textview layer] setCornerRadius:15];
[dynamicImg addSubview:textview];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//cameragalleryimage.image =[info objectForKey:UIImagePickerControllerOriginalImage];
UIImage *image=[info objectForKey:#"UIImagePickerControllerOriginalImage"];
cameragalleryimage.image=image;
[array_Image addObject:image];
picker.delegate =self;
[picker dismissViewControllerAnimated:NO completion:nil];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:NO completion:nil];
}
-(void)textViewDidBeginEditing:(UITextField *)textView
{
CGRect textViewRect =
[self.view.window convertRect:textView.bounds fromView:textView];
CGRect viewRect =
[self.view.window convertRect:self.view.bounds fromView:self.view];
CGFloat midline = textViewRect.origin.y + 0.5 * textViewRect.size.height;
CGFloat numerator =
midline - viewRect.origin.y
- MINIMUM_SCROLL_FRACTION * viewRect.size.height;
CGFloat denominator =
(MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
* viewRect.size.height;
CGFloat heightFraction = numerator / denominator;
if (heightFraction < 0.0)
{
heightFraction = 0.0;
}
else if (heightFraction > 1.0)
{
heightFraction = 1.0;
}
animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
CGRect viewFrame = self.view.frame;
viewFrame.origin.y -= animatedDistance;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
[self.view setFrame:viewFrame];
[UIView commitAnimations];
}
-(void)textViewDidEndEditing:(UITextField *)textView
{
CGRect viewFrame = self.view.frame;
viewFrame.origin.y += animatedDistance;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
[self.view setFrame:viewFrame];
[UIView commitAnimations];
}
static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
{
//FOR ASSIGINING SPACE AND LENGTH FOR TEXT VIEW WITH CONDITION
if(textView.text.length >=100)
{
[textView resignFirstResponder];
return NO;
}
if([text rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]].location == NSNotFound)
{
return YES;
}
[textView resignFirstResponder];
return NO;
}
-(void)startSignificantChangeUpdates
{
if ([CLLocationManager locationServicesEnabled])
{
if (!self.locationManager)
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
[self.locationManager startMonitoringSignificantLocationChanges];
}
}
-(void)stopSignificantChangesUpdates
{
[self.locationManager stopUpdatingLocation];
self.locationManager = nil;
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations lastObject];
CLGeocoder *geocoder =[[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks,NSError *error)
{
CLPlacemark *placemark = placemarks[0];
NSDictionary *addressDictionary =[placemark addressDictionary];
NSString *city = addressDictionary[(NSString *)kABPersonAddressCityKey];
NSString *state = addressDictionary[(NSString *)kABPersonAddressStateKey];
NSString *street=addressDictionary[(NSString *)kABPersonAddressStreetKey];
NSString *country = placemark.country;
locationLabel.text=[NSString stringWithFormat:#"%# %# %# %#",street,city,state,country];
}];
[self stopSignificantChangesUpdates];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (IBAction)switchaction:(id)sender
{
if(swi.isOn)
{
[self tapdetected1];
}
else
{
[self tapdetected2];
}
}
-(void)prepareDatabase
{
NSMutableArray *arrayTotalImage =[[NSMutableArray alloc]init];
for (UIImage *img in array_Image)
{
NSString *str =[BusinessModeOne getSavedPhotoPath:img];
[arrayTotalImage addObject:str];
}
NSLog(#"%#",arrayTotalImage);
if ([arrayTotalImage count] ==0)
{
BusinessModeOne *businessDBOne = [[BusinessModeOne alloc]init];
businessDBOne.txtfldstrOne =textfld.text;
businessDBOne.txtviewstrOne =textview.text;
businessDBOne.arrayOne=nil;
businessDBOne.strLocationOne=locationLabel.text;
businessDBOne.strDateOne=dateLabel.text;
businessDBOne.strTimeOne=timeLabel.text;
[SqliteDBOne insertDataintoSqliteOne:businessDBOne];
}
else
{
for (int i=0; i<[arrayTotalImage count]; i++)
{
BusinessModeOne *businessDBOne =[[BusinessModeOne alloc]init];
businessDBOne.txtfldstrOne=textfld.text;
NSLog(#"the textfield is == %#",businessDBOne.txtfldstrOne);
businessDBOne.txtviewstrOne=textview.text;
NSLog(#"the textview is ==%#", businessDBOne.txtviewstrOne);
businessDBOne.arrayOne =[arrayTotalImage objectAtIndex:i];
businessDBOne.strLocationOne=locationLabel.text;
NSLog(#"the location is == %#",businessDBOne.strLocationOne);
businessDBOne.strDateOne=dateLabel.text;
NSLog(#"the date is== %#", businessDBOne.strDateOne);
businessDBOne.strTimeOne=timeLabel.text;
NSLog(#"the time is ==%#",businessDBOne.strTimeOne);
[SqliteDBOne insertDataintoSqliteOne:businessDBOne];
}
}
}
-(IBAction)backbutton:(id)sender
{
[self.navigationController popToRootViewControllerAnimated:YES];
[self prepareDatabase];
}
just replace your coding
-(void)tapdetected3
{
//For dynamically creating imageview
dynamicImg =[[UIImageView alloc]init];
dynamicImg.frame=CGRectMake(10, 100, 280, 260);
[dynamicImg setUserInteractionEnabled:YES];
dynamicImg.image =cameragalleryimage.image;
[self.view addSubview:dynamicImg]; //add the image view to self.view
UITapGestureRecognizer *tapgesture4 =[[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(tapdetected4)];
tapgesture4.numberOfTapsRequired=1;
tapgesture4.numberOfTouchesRequired=1;
dynamicImg.userInteractionEnabled =YES;
[dynamicImg addGestureRecognizer:tapgesture4];
}

ViewDidAppear is not being called

I'm using a delegate UITabbarController with transition animation like this:
-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
NSArray *tabViewControllers = tabBarController.viewControllers;
UIView * fromView = tabBarController.selectedViewController.view;
UIView * toView = viewController.view;
if (fromView == toView)
return TRUE;
NSUInteger fromIndex = [tabViewControllers indexOfObject:tabBarController.selectedViewController];
NSUInteger toIndex = [tabViewControllers indexOfObject:viewController];
[UIView transitionFromView:fromView
toView:toView
duration:0.3
options: toIndex > fromIndex ? UIViewAnimationOptionTransitionFlipFromLeft : UIViewAnimationOptionTransitionFlipFromRight
completion:^(BOOL finished) {
if (finished) {
tabBarController.selectedIndex = toIndex;
}
}];
return true;
}
Only this broke my entire ViewDidAppear on the views. I'm resetting the UIWebView to the homepage when switching between tabs, but this doesn't work anymore. Any suggestions? Here's my VieDidLoad:
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
_progressProxy = [[NJKWebViewProgress alloc] init];
_webView.delegate = _progressProxy;
_progressProxy.webViewProxyDelegate = self;
_progressProxy.progressDelegate = self;
[self loadSite];
[TestFlight passCheckpoint:#"Bekijkt homepage"];
}
[self loadSite]; is defined as:
-(void)loadSite
{
NSString *dealerurl = [[NSUserDefaults standardUserDefaults] stringForKey:#"name_preference"];
NSString *urlAddress= #"http://www.sportdirect.com/shop/";
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlAddress]];
[_webView loadRequest:req];
[[_webView scrollView] setBounces: NO];
}
Thanks in advance.
Change:
[_webView loadRequest:req];
to this:
self.webView loadRequest:req;
I think this will undo the nil.

Tap gesture causes strange behavior

I’m building a reaction test that requires the user to tap on the target dot, while other non-target dots come down. It works most of the time but sometimes after tapping on a target dot it will display several other dots with weird behavior. I’ve been looking at the code for days and I can’t find the problem. Does anyone have any suggestions?
Thanks much. Here’s the code.
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// single tap gesture recognizer
self.myTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(theTap:)];
self.myTap.numberOfTapsRequired = 1;
[self.firstView addGestureRecognizer:self.myTap];
self.myTap.enabled = NO;
self.colorToHit = self.colorFromPreviousController;
[self KickOff];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.holdTheReactionTimes = [[NSMutableArray alloc] initWithCapacity:50];
self.firstTime = YES;
numberOfTries = 0;
}
#pragma mark - Utility Methods
- (void)setRandomLocationForView:(UIView *)view
{
CGRect sinkBounds = CGRectInset(self.firstView.bounds, view.frame.size.width/2, view.frame.size.height/2);
CGFloat x = arc4random() % (int)sinkBounds.size.width + view.frame.size.width/2;
CGFloat y = arc4random() % (int)sinkBounds.size.height + view.frame.size.height/2;
view.center = CGPointMake(x, y);
}
- (void)addLabel
{
[self stopDraining];
static NSArray *buttons = nil;
buttons = [[NSArray alloc] initWithObjects:
#"XX.png",
#"YY.png",
#"ZZ.png",
nil];
int theIndex = arc4random()%[buttons count];
NSLog(#"the index: %d", theIndex);
NSString *theImageName = [buttons objectAtIndex:theIndex];
CGRect anotherFrame = CGRectMake(10, 10, 64, 64);
UIView *anotherView = [[UIView alloc] initWithFrame:anotherFrame]
UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(-2, -2, 64, 64)];
imageView1.image = [UIImage imageNamed:theImageName];
[anotherView addSubview:imageView1];
[self setRandomLocationForView:anotherView];
[self.firstView addSubview:anotherView];
NSDate *date = [NSDate date];
timeOne = [date timeIntervalSince1970];
if (theIndex == self.colorToHit) {
NSLog(#"the right color");
self.isThisTheRightColor = YES;
self.myTap.enabled = YES;
numberOfTries += 1;
} else {
NSLog(#"the wrong color");
self.isThisTheRightColor = NO;
self.myTap.enabled = NO;
[self startDraining];
}
}
#pragma mark - View Animation
#define ANIMATE_DURATION 6.0
#define SLEEP_INTERVAL 0.5
- (void)theTap:(UITapGestureRecognizer *)gesture
{
NSLog(#"Tapped");
float tapInterval = 0;
CGPoint tapLocation = [gesture locationInView:self.firstView];
for (UIView *view in self.firstView.subviews) {
if (CGRectContainsPoint(view.frame, tapLocation)) {
NSLog(#"we hit one");
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate); // added this 4-27
if (self.firstTime) {
NSDate *date = [NSDate date];
timeTwo = [date timeIntervalSince1970];
NSLog(#"TAP First time: %f", timeTwo);
self.firstTime = NO;
} else {
NSDate *date = [NSDate date];
timeTwo = [date timeIntervalSince1970];
NSLog(#"Second time: %f", timeTwo);
}
tapInterval = (timeTwo - timeOne);
NSLog(#"Time Interval: %f", tapInterval);
[view removeFromSuperview];
[self writeTimeStampToArray:tapInterval];
}
}
}
- (void)KickOff
{
for (UIView *view in self.firstView.subviews) {
[view removeFromSuperview];
}
if (self.firstView.window) {
[self addLabel];
}
}
- (void)writeTimeStampToArray:(float)timeStamp
{
NSNumber *timeObject = [NSNumber numberWithFloat: timeStamp];
[self.holdTheReactionTimes addObject:timeObject];
if (numberOfTries < NUMBER_OF_TRIES) {
[self addLabel];
} else {
[self nextScreen];
}
}
- (void)nextScreen
{
[self performSegueWithIdentifier: #"viewsummary" sender: self];
}
}
}
#pragma mark - Flipside View
- (void)ReactionViewControllerDidFinish:(int)trynumber
{
self.tryNumberInt = trynumber;
[self dismissViewControllerAnimated:YES completion:nil];
}
#define COUNTER 4
//////////////
// drain logic
- (void)drain:(NSTimer *)timer
{
[self drain];
}
#define DRAIN_DURATION 2.0
- (void)startDraining
{
self.drainTimer = [NSTimer scheduledTimerWithTimeInterval:DRAIN_DURATION/3
target:self
selector:#selector(drain:)
userInfo:nil
repeats:YES];
}
- (void)stopDraining
{
[self.drainTimer invalidate];
}
- (void)drain
{
for (UIView *view in self.firstView.subviews) {
CGAffineTransform transform = view.transform;
if (CGAffineTransformIsIdentity(transform)) {
UIViewAnimationOptions options = UIViewAnimationOptionCurveLinear;
[UIView animateWithDuration:DRAIN_DURATION/3 delay:0 options:options animations:^{
view.transform = CGAffineTransformRotate(CGAffineTransformScale(transform, 0.7, 0.7), 2*M_PI/3);
} completion:^(BOOL finished) {
if (finished) {
[UIView animateWithDuration:DRAIN_DURATION/3 delay:0 options:options animations:^{
view.transform = CGAffineTransformRotate(CGAffineTransformScale(transform, 0.4, 0.4), -2*M_PI/3);
} completion:^(BOOL finished) {
if (finished) {
[UIView animateWithDuration:DRAIN_DURATION/3 delay:0 options:options animations:^{
view.transform = CGAffineTransformScale(transform, 0.1, 0.1);
} completion:^(BOOL finished) {
if (finished) [view removeFromSuperview];
}];
}
}];
}
}];
}
}
[self addLabel];
}

Resources