Tap gesture causes strange behavior - ios

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

Related

Issue in ScrollTabletoBottom

I'm developing a chat app in ios and I have custom tableview and UIView with GrowingTextview and button on the bottom. I would like to move the Tableview to bottom when SendButton is Pressed.But it's not scrolling properly to the bottom.
My Code,
-(void) textViewDidChange:(UITextView *)textView
{
CGFloat maxHeight = [JSMessageInputView maxHeight];
CGSize size = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, maxHeight)];
CGFloat textViewContentHeight = size.height;
// End of textView.contentSize replacement code
BOOL isShrinking = textViewContentHeight < self.previousTextViewContentHeight;
CGFloat changeInHeight = textViewContentHeight - self.previousTextViewContentHeight;
if(!isShrinking && self.previousTextViewContentHeight == maxHeight) {
changeInHeight = 0;
}
else {
changeInHeight = MIN(changeInHeight, maxHeight - self.previousTextViewContentHeight);
}
if(changeInHeight != 0.0f) {
// if(!isShrinking)
// [self.inputToolBarView adjustTextViewHeightBy:changeInHeight];
[UIView animateWithDuration:0.25f
animations:^{
UIEdgeInsets insets = UIEdgeInsetsMake(0.0f,
0.0f,
self.ChatTableView.contentInset.bottom + changeInHeight,
0.0f);
self.ChatTableView.contentInset = insets;
self.ChatTableView.scrollIndicatorInsets = insets;
[self scrollToBottomAnimated:NO];
if(isShrinking) {
// if shrinking the view, animate text view frame BEFORE input view frame
[self.inputToolBarView adjustTextViewHeightBy:changeInHeight];
}
CGRect inputViewFrame = self.inputToolBarView.frame;
self.inputToolBarView.frame = CGRectMake(0.0f,
inputViewFrame.origin.y - changeInHeight,
inputViewFrame.size.width,
inputViewFrame.size.height + changeInHeight);
if(!isShrinking) {
[self.inputToolBarView adjustTextViewHeightBy:changeInHeight];
}
}
completion:^(BOOL finished) {
}];
self.previousTextViewContentHeight = MIN(textViewContentHeight, maxHeight);
}
self.inputToolBarView.sendButton.enabled = ([textView.text trimWhitespace].length > 0);
}
-(void)textViewDidBeginEditing:(UITextView *)textView
{
if(!self.previousTextViewContentHeight)
self.previousTextViewContentHeight = textView.contentSize.height;
[self scrollToBottomAnimated:YES];
}
- (void)scrollToBottomAnimated:(BOOL)animated
{
NSInteger rows = [self.ChatTableView
numberOfRowsInSection:0];
if(rows > 0) {
[self.ChatTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0]
atScrollPosition:UITableViewScrollPositionBottom
animated:animated];
}
}
- (void)keyboardWillShowHide:(NSNotification *)notification
{
CGRect keyboardRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
UIViewAnimationCurve curve = [[notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:duration
delay:0.0f
options:[UIView animationOptionsForCurve:curve]
animations:^{
CGFloat keyboardY = [self.view convertRect:keyboardRect fromView:nil].origin.y;
CGRect inputViewFrame = self.inputToolBarView.frame;
CGFloat inputViewFrameY = keyboardY - inputViewFrame.size.height;
// for ipad modal form presentations
CGFloat messageViewFrameBottom = self.view.frame.size.height - INPUT_HEIGHT;
if(inputViewFrameY > messageViewFrameBottom)
inputViewFrameY = messageViewFrameBottom;
self.inputToolBarView.frame = CGRectMake(inputViewFrame.origin.x,
inputViewFrameY,
inputViewFrame.size.width,
inputViewFrame.size.height);
UIEdgeInsets insets = self.originalTableViewContentInset;
insets.bottom = self.view.frame.size.height - self.inputToolBarView.frame.origin.y - inputViewFrame.size.height;
self.ChatTableView.contentInset = insets;
self.ChatTableView.scrollIndicatorInsets = insets;
}
completion:^(BOOL finished) {
}];
}
-(void)sendPressed:(id)sender {
NSString*TextString;
TextString=_inputToolBarView.textView.text;
NSString *rawString = [self.inputToolBarView.textView text];
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace];
_inputToolBarView.textView.text = trimmed;
if ([TextString isEqualToString:#""]) {
NSLog(#"Empty");
}
else
{
if([sharedClass.unmatchcheckStr isEqualToString:#"unMatched"])
{
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:[NSString stringWithFormat:#"%# Unmatched you",_userName]
message:[NSString stringWithFormat:#"%#",UNMATCH_CHAT_ALERT]
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* okButton = [UIAlertAction
actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
sharedClass.unmatchcheckStr=#"";
[[ChatConnectClass sharedManager]deleteUserRecord:[NSString stringWithFormat:#"%#",_toUserID]];
[self performSegueWithIdentifier:#"match" sender:self];
}];
[alert addAction:okButton];
[self presentViewController:alert animated:YES completion:nil];
}
else
{
NSDate *currentDateNSDate = [NSDate date];
NSDateFormatter *dateFormatterCurrent = [[NSDateFormatter alloc] init];
[dateFormatterCurrent setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *time = [dateFormatterCurrent stringFromDate:currentDateNSDate];
NSDate *currentDate = [dateFormatterCurrent dateFromString:time];
int random = arc4random() % 10000;
NSString *messageId = [NSString stringWithFormat:#"%#%lu%d",[[MontageUserDefaults getBasicInfo] valueForKey:kMemberId],(unsigned long)([[NSDate date] timeIntervalSince1970]*10.0),random];
NSLog(#"MSG id Sent : %#",messageId);
[[ChatConnectClass sharedManager]insertNewMessages:[NSString stringWithFormat:#"%#",_toUserID] message:_inputToolBarView.textView.text messageId:messageId date:currentDate isFrom:NO msgStatus:#"Sending"];
[[ChatConnectClass sharedManager] sendMessage:_inputToolBarView.textView.text messageId:messageId To:self.toUserID];
array_recieveMessage.array = [[ChatConnectClass sharedManager] fetchMessagesUsingUserid:[NSString stringWithFormat:#"%#",_toUserID]];
[self.ChatTableView reloadData];
[self scrollToBottomAnimated:YES];
_inputToolBarView.textView.text=#"";
}
}
}

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.

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

Trouble hiding iAd banner and displaying UIWebView in its place

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

Truncated tweets iOS

I am putting a twitter feed in my app and no matter what I have tried to do to get the tweets to display in their entirety, I have not been entirely successful. Most tweets show up fine but it's the really long ones that have given me a headache. I thought it was because I was somehow not getting enough lines in my textLabel, but I noticed that if a user has elongated their tweet by hitting enter multiple times the tweets would show up fine. Which leads me to believe somehow it is truncating after a certain amount of characters. I don't know if I'm doing something wrong or if this is just an issue with twitter. If anyone can see anything in my code that is wrong, or could be changed to fix this, please let me know. Thank you
#import "TwitterFeedTVC.h"
#import "TweetVC.h"
#import <QuartzCore/QuartzCore.h>
#import "GTMNSString+HTML.h"
#define REFRESH_HEADER_HEIGHT 52.0f
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 10.0f
#implementation TwitterFeedTVC
#synthesize textPull, textRelease, textLoading, refreshHeaderView, refreshLabel, refreshArrow, refreshSpinner, twitterFeedName, twitterFeedTitle;
- (id)initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self != nil)
{
[self setupStrings];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self != nil)
{
[self setupStrings];
}
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self != nil)
{
[self setupStrings];
}
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.twitterFeedTitle.text = self.twitterFeedName;
self.navigationItem.title = self.twitterFeedName;
[self fetchTweets];
[self addPullToRefreshHeader];
}
- (void)fetchTweets
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://api.twitter.com/1/statuses/user_timeline.json?include_rts=true&screen_name=johnnelm9r&count=100"]];
if (data == nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning"
message:#"Twitter Is Not Responding. Please Try Again Later!"
delegate:self
cancelButtonTitle:#"Kali Baby"
otherButtonTitles: nil];
[alert show];
}
else
{
NSError *error;
tweets = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
- (void)viewDidUnload
{
[super viewDidUnload];
textPull = nil;
textRelease = nil;
textLoading = nil;
refreshHeaderView = nil;
refreshLabel = nil;
refreshArrow = nil;
refreshSpinner = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tweets.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSString *text = [tweet objectForKey:#"text"];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), CGFLOAT_MAX);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
CGFloat height = MAX(size.height, 44.0f);
return height + ((CELL_CONTENT_MARGIN * 2) + 9);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TweetCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[dateFormatter setDateFormat:#"EEE MMM dd HH:mm:ss +0000 yyyy"];
NSDate *currentDate = [dateFormatter dateFromString:[tweet objectForKey:#"created_at"]];
NSDate *todayDate = [NSDate date];
NSString *date = [dateFormatter stringFromDate:currentDate];
double timeInterval = [currentDate timeIntervalSinceDate:todayDate];
timeInterval = timeInterval * -1;
if (timeInterval < 1)
{
date = #"never";
}
else if (timeInterval <60)
{
date = #"less than a minute ago";
}
else if (timeInterval <3600)
{
int diff = round(timeInterval / 60);
date = [NSString stringWithFormat:#"%d minutes ago", diff];
}
else if (timeInterval < 86400)
{
int diff = round(timeInterval / 60 / 60);
date = [NSString stringWithFormat:#"%d hours ago", diff];
}
else if (timeInterval < 2629743)
{
int diff = round(timeInterval / 60 / 60 / 24);
date = [NSString stringWithFormat:#"%d days ago", diff];
}
else
{
date = #"never";
}
cell.textLabel.text = [[tweet objectForKey:#"text"] gtm_stringByUnescapingFromHTML];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", date];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *imageUrl = [[tweet objectForKey:#"user"] objectForKey:#"profile_image_url"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = [UIImage imageWithData:data];
[cell addSubview:cell.imageView];
});
});
return cell;
}
- (void)setupStrings
{
textPull = #"Pull Down To Be Fresh...";
textRelease = #"Release To Be Fresh...";
textLoading = #"Getting Loaded...";
}
- (void)addPullToRefreshHeader
{
refreshHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0 - REFRESH_HEADER_HEIGHT, 320, REFRESH_HEADER_HEIGHT)];
refreshHeaderView.backgroundColor = [UIColor clearColor];
refreshLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, REFRESH_HEADER_HEIGHT)];
refreshLabel.backgroundColor = [UIColor clearColor];
refreshLabel.font = [UIFont boldSystemFontOfSize:12.0];
refreshLabel.textAlignment = UITextAlignmentCenter;
refreshArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"KrizzOpener.png"]];
refreshArrow.frame = CGRectMake(floorf((REFRESH_HEADER_HEIGHT - 27) / 2),
(floorf(REFRESH_HEADER_HEIGHT - 44) / 2),
27, 44);
refreshSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
refreshSpinner.frame = CGRectMake(floorf(floorf(REFRESH_HEADER_HEIGHT - 20) / 2), floorf((REFRESH_HEADER_HEIGHT - 20) / 2), 20, 20);
refreshSpinner.hidesWhenStopped = YES;
[refreshHeaderView addSubview:refreshLabel];
[refreshHeaderView addSubview:refreshArrow];
[refreshHeaderView addSubview:refreshSpinner];
[self.tableView addSubview:refreshHeaderView];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
if (isLoading) return;
isDragging = YES;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (isLoading) {
if (scrollView.contentOffset.y > 0)
self.tableView.contentInset = UIEdgeInsetsZero;
else if (scrollView.contentOffset.y >= -REFRESH_HEADER_HEIGHT)
self.tableView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
} else if (isDragging && scrollView.contentOffset.y < 0) {
[UIView beginAnimations:nil context:NULL];
if (scrollView.contentOffset.y < -REFRESH_HEADER_HEIGHT) {
refreshLabel.text = self.textRelease;
} else {
refreshLabel.text = self.textPull;
}
[UIView commitAnimations];
}
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
if (isLoading) return;
isDragging = NO;
if (scrollView.contentOffset.y <= -REFRESH_HEADER_HEIGHT)
{
[self startLoading];
}
}
- (void)startLoading {
isLoading = YES;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
self.tableView.contentInset = UIEdgeInsetsMake(REFRESH_HEADER_HEIGHT, 0, 0, 0);
refreshLabel.text = self.textLoading;
refreshArrow.hidden = YES;
[refreshSpinner startAnimating];
[UIView commitAnimations];
[self refresh];
}
- (void)stopLoading {
isLoading = NO;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.3];
[UIView setAnimationDidStopSelector:#selector(stopLoadingComplete:finished:context:)];
self.tableView.contentInset = UIEdgeInsetsZero;
UIEdgeInsets tableContentInset = self.tableView.contentInset;
tableContentInset.top = 0.0;
self.tableView.contentInset = tableContentInset;
[UIView commitAnimations];
}
- (void)stopLoadingComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
refreshLabel.text = self.textPull;
refreshArrow.hidden = NO;
[refreshSpinner stopAnimating];
}
- (void)refresh {
[self fetchTweets];
[self performSelector:#selector(stopLoading) withObject:nil afterDelay:2.7];
}
#pragma mark - Table view delegate
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"tweetVC"])
{
NSInteger row = [[self tableView].indexPathForSelectedRow row];
NSDictionary *tweet = [tweets objectAtIndex:row];
TweetVC *tweetVC = segue.destinationViewController;
tweetVC.detailItem = tweet;
}
}
After a lot of investigation I found an article somewhere that said there is a difference between the text key and the retweeted_status.text key. The tweets being truncated were, in fact, retweets from the user using the text key. However, the retweeted_status.text key is only the tweet that was retweeted, without the user who originally tweeted it. That sucks because the retweeted_status.text key is NOT truncated. Ahhh, the joys of programming. Hopefully the new twitter API will address this. I hope this answer helps somebody.
Here is the link to what I found in case anyone is interested: http://code.google.com/p/twitter-api/issues/detail?id=2261
I haven't gone through your code, but I thought of mentioning this point that Twitter only allows tweet 140 characters long! This is the basic rule of a tweet. So no matter what you do tweet with mode than 140 characters will be truncated.
I hope this is not the issue?

Resources