iOS background view not updated using NSTimer while scanning the bluetooth DEVICE - ios

I am trying to work on getting the bluetooth scanning page to pair the BLE device using bluetooth.
I have found the NSUInteger [ _ble.scannedPeripheral count ] do change while scanning. However, when it comes to the execution, the background view images and pages cannot even change. Would you please tell me other wayout make the page change if the variable showing available BLE devices changes from 0 to 1,2 or 3 ?
The below is my code : (Only relevant)
- (void)viewDidAppear:(BOOL)animated
{
if (_ble)
{
_ble.delegate = (id) self;
_ble.btStatus = BT_IDLE;
[_ble startScanning];
}
[NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:#selector(reloadData) userInfo:nil repeats:YES];
}
-(void) reloadData {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// time consuming workout
dispatch_async(dispatch_get_main_queue(), ^{
// UI update workout for bluetooth scanning
if( [ _ble.scannedPeripheral count ] > 0 ){
[self stopAnimatingImages];
[self setTapDemo : [UIImage imageNamed:#"pairing_d.png"] : #"Pairing" : #"#C4CCCF"] ;
}else{
[self setTapDemo : [self loadingImage] : #"Pairing" : #"#C4CCCF"] ;
[self animateImages];
}
});
});
}
- (void) setTapDemo: (UIImage *) cover : (NSString *) title : (NSString *) colorHex{
image = [UIImage imageNamed:#"shaded_cal.png"];
imageA = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
_container = [[UIView alloc] initWithFrame:[self.view bounds]];
[imageA setImage:cover];
imageA.userInteractionEnabled = YES;
UITapGestureRecognizer *myGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(touchesBegan:)];
myGesture.numberOfTapsRequired = 1;
myGesture.delegate=self;
[imageA addGestureRecognizer:myGesture];
[imageA setContentMode:UIViewContentModeScaleAspectFill];
myLabelQ = [self constructLabelT:title:0.27:0.08: colorHex:25];
myLabelBack =[self constructLabelT:#"BACK":0.04:0.01:#"#C4CCCF":18] ;
if( bleCount > 0){
for(NSUInteger i = 0 ; i < [ _ble.scannedPeripheral count ] ; i ++){
DevicePeriperal *device;
NSString *uuid = [_ble.scannedPeripheralKey objectAtIndex:i];
NSLog (#"device uuid = %#", uuid);
if (uuid)
{
device = [_ble.scannedPeripheral objectForKey:uuid];
NSData * ssx = device.advertdata ;
device.rowIndex = i;
NSLog (#"device advert = %#", ssx);
if([ssx length] > 0){
NSData *macD = [ssx subdataWithRange:NSMakeRange(0, 6)];
NSData *pairD = [ssx subdataWithRange:NSMakeRange(6, 1)];
NSString* newStr = [self hexRepresentationWithSpaces:pairD : NO];
NSString* newMAC = [self hexRepresentationWithSpaces:macD : YES];
NSLog (#"newStr = %#", newStr );
NSLog (#"newMAC = %#", newMAC );
_checkSumByte = [self calculateChecksum:newMAC];
}
NSLog (#"device = %#", device.uuid);
if (device )
{
UIImage *dImage = [UIImage imageNamed:#"device_u.png"];
float change = 0.15*i;
float yPosition = 0.25 + change ;
[imageA addSubview:[self deviceGet:dImage:device.deviceName: 0.40 : yPosition : #"#C4CCCF"]];
}
}
}
//UIImage *dImage = [UIImage imageNamed:#"device_u.png"];
//[imageA addSubview:[self deviceGet:dImage:#"x": 0.40 : 0.25 : #"#C4CCCF"]];
//[imageA addSubview:[self deviceGet:dImage:#"x": 0.40 : 0.40 : #"#C4CCCF"]];
//[imageA addSubview:[self deviceGet:dImage:#"x": 0.40 : 0.55 : #"#C4CCCF"]];
//[imageA addSubview:myLabelS3];
myLabelS1 = [self constructLabelT:#"SPOTTED":0.27:0.723: colorHex:25];
myLabelS2 =[self constructLabelT:#"(choose the one you want to connect)":0.55:0.76:#"#C4CCCF":10] ;
myLabelS3 = [self constructLabelT:#"devices":0.30:0.76: colorHex:25];
}else{
myLabelS1 = [self constructLabelT:#"SCANNING":0.27:0.723: colorHex:25];
myLabelS2 =[self constructLabelT:#"devices":0.51:0.76:#"#C4CCCF":25] ;
myLabelS3 = [self constructLabelT:#"for":0.30:0.76: colorHex:25];
}
[imageA addSubview:myLabelQ];
[imageA addSubview:myLabelBack];
[imageA addSubview:myLabelS1];
[imageA addSubview:myLabelS2];
[imageA addSubview:myLabelS3];
[_container addSubview:imageA];
[self.view addSubview:_container];
[self.view sendSubviewToBack:_container];
}

Each time you call setTapDemo :::, you will create a new _container view and it will be added to self.view . Because you never remove the old one from super view before initialise it again, self.view contains more and more subviews by timer repeats which will finally consume all memory then your app will crash.
Further, [self.view sendSubviewToBack:_container] was called each time while timer was fired, and you never remove your old _container, so any new _container would be hidden behind as result.
In conclusion, I guess you did create updated _container while [ _ble.scannedPeripheral count ] was changed but it was staying behind other subviews. So your may try to modify the code like this:
- (void) setTapDemo: (UIImage *) cover : (NSString *) title : (NSString *) colorHex{
// remove any old _container view
if (_container) [_container removeFromSuperView];
image = [UIImage imageNamed:#"shaded_cal.png"];
imageA = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
_container = [[UIView alloc] initWithFrame:[self.view bounds]];
[imageA setImage:cover];
imageA.userInteractionEnabled = YES;
UITapGestureRecognizer *myGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(touchesBegan:)];
myGesture.numberOfTapsRequired = 1;
myGesture.delegate=self;
[imageA addGestureRecognizer:myGesture];
[imageA setContentMode:UIViewContentModeScaleAspectFill];
myLabelQ = [self constructLabelT:title:0.27:0.08: colorHex:25];
myLabelBack =[self constructLabelT:#"BACK":0.04:0.01:#"#C4CCCF":18] ;
if( bleCount > 0){
for(NSUInteger i = 0 ; i < [ _ble.scannedPeripheral count ] ; i ++){
DevicePeriperal *device;
NSString *uuid = [_ble.scannedPeripheralKey objectAtIndex:i];
NSLog (#"device uuid = %#", uuid);
if (uuid)
{
device = [_ble.scannedPeripheral objectForKey:uuid];
NSData * ssx = device.advertdata ;
device.rowIndex = i;
NSLog (#"device advert = %#", ssx);
if([ssx length] > 0){
NSData *macD = [ssx subdataWithRange:NSMakeRange(0, 6)];
NSData *pairD = [ssx subdataWithRange:NSMakeRange(6, 1)];
NSString* newStr = [self hexRepresentationWithSpaces:pairD : NO];
NSString* newMAC = [self hexRepresentationWithSpaces:macD : YES];
NSLog (#"newStr = %#", newStr );
NSLog (#"newMAC = %#", newMAC );
_checkSumByte = [self calculateChecksum:newMAC];
}
NSLog (#"device = %#", device.uuid);
if (device )
{
UIImage *dImage = [UIImage imageNamed:#"device_u.png"];
float change = 0.15*i;
float yPosition = 0.25 + change ;
[imageA addSubview:[self deviceGet:dImage:device.deviceName: 0.40 : yPosition : #"#C4CCCF"]];
}
}
}
//UIImage *dImage = [UIImage imageNamed:#"device_u.png"];
//[imageA addSubview:[self deviceGet:dImage:#"x": 0.40 : 0.25 : #"#C4CCCF"]];
//[imageA addSubview:[self deviceGet:dImage:#"x": 0.40 : 0.40 : #"#C4CCCF"]];
//[imageA addSubview:[self deviceGet:dImage:#"x": 0.40 : 0.55 : #"#C4CCCF"]];
//[imageA addSubview:myLabelS3];
myLabelS1 = [self constructLabelT:#"SPOTTED":0.27:0.723: colorHex:25];
myLabelS2 =[self constructLabelT:#"(choose the one you want to connect)":0.55:0.76:#"#C4CCCF":10] ;
myLabelS3 = [self constructLabelT:#"devices":0.30:0.76: colorHex:25];
}else{
myLabelS1 = [self constructLabelT:#"SCANNING":0.27:0.723: colorHex:25];
myLabelS2 =[self constructLabelT:#"devices":0.51:0.76:#"#C4CCCF":25] ;
myLabelS3 = [self constructLabelT:#"for":0.30:0.76: colorHex:25];
}
[imageA addSubview:myLabelQ];
[imageA addSubview:myLabelBack];
[imageA addSubview:myLabelS1];
[imageA addSubview:myLabelS2];
[imageA addSubview:myLabelS3];
[_container addSubview:imageA];
//[self.view addSubview:_container];
//[self.view sendSubviewToBack:_container];
// One line of code can do this trick
[self.view insertSubview:_container atIndex:0];
}

Related

Images on horizontal scroll view according to clicked image

I have four images on a Viewcontroller A .On the click of those images Viewcontroller B having UIScrollView presents that has image view and it shows all those four imgaes....Image1 ,image 2,image 3,image 4.
I want that when image 2 is clicked then image 2 appeas as the first image on Viewcontroller B ,then image 3,then image 4...Also,when user moves left then it shows previous images including image1 too.
I have searched a lot but couldn't find solution to this problem Kindly.help
The code I have used are as follows:
- (void)viewDidLoad {
[super viewDidLoad];
width = [UIScreen mainScreen].bounds.size.width;
height = [UIScreen mainScreen].bounds.size.height;
_scroller = [[UIScrollView alloc]initWithFrame:
CGRectMake(0,64,width,height)];
_scroller.contentSize=CGSizeMake(pageCount*_scroller.bounds.size.width,_scroller.bounds.size.height);
_scroller.pagingEnabled=YES;
_scroller.showsHorizontalScrollIndicator=YES;
CGRect ViewSize=_scroller.bounds;
NSArray *imgArray = [self.tripDetails valueForKey:#"Flightimageurl"];
for(int i=0;i<[imgArray count];i++)
{
UIImageView *imgView1=[[UIImageView alloc]initWithFrame:ViewSize];
NSString *ImageURL = [imgArray objectAtIndex:i];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
imgView1.image=[UIImage imageWithData:imageData];
[_scroller addSubview:imgView1];
[self.view addSubview:_scroller];
ViewSize =CGRectOffset(ViewSize,_scroller.bounds.size.width,0);
}
}
Use This Code It will be helpful to you
-(void)singleTapping:(UIGestureRecognizer *)recognizer {
int imageTag = (int) recognizer.view.tag;
NSDictionary *dictCurrentWish = [arrLatestScrollData objectAtIndex:pageNumberSaved];
scrollimagePostView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0, kSCREEN_WIDTH, kSCREEN_HEIGHT)];
scrollimagePostView.pagingEnabled=YES;
scrollimagePostView.delegate=self;
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleGesture:)];
[scrollimagePostView addGestureRecognizer:gr];
NSMutableArray *arrTotalImages = [[NSMutableArray alloc]initWithCapacity:0];
[arrTotalImages addObject:[dictCurrentWish objectForKey:#"pic1"]];
[arrTotalImages addObject:[dictCurrentWish objectForKey:#"pic2"]];
[arrTotalImages addObject:[dictCurrentWish objectForKey:#"pic3"]];
[arrTotalImages addObject:[dictCurrentWish objectForKey:#"pic4"]];
int x=0;
CGRect innerScrollFrame = scrollimagePostView.bounds;
for (int i=0; i<arrTotalImages.count; i++) {
imgViewPost=[[UIImageView alloc]initWithFrame:CGRectMake(x, 60, kSCREEN_WIDTH,kSCREEN_HEIGHT-90)];
NSString *strImage =[NSString stringWithFormat:#"%#", [arrTotalImages objectAtIndex:i]];
NSString *strURL=[strImage stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSURL* urlAddress1 = [[NSURL alloc] initWithString:strURL];
[imgViewPost sd_setImageWithURL:urlAddress1 placeholderImage:wishPlaceHolderImage];
imgViewPost.contentMode = UIViewContentModeScaleAspectFit;
imgViewPost.tag = VIEW_FOR_ZOOM_TAG;
UIScrollView *pageScrollView = [[UIScrollView alloc]
initWithFrame:innerScrollFrame];
pageScrollView.minimumZoomScale = 1.0f;
pageScrollView.maximumZoomScale = 6.0f;
pageScrollView.zoomScale = 1.0f;
pageScrollView.contentSize = imgViewPost.bounds.size;
pageScrollView.delegate = self;
pageScrollView.showsHorizontalScrollIndicator = NO;
pageScrollView.showsVerticalScrollIndicator = NO;
[pageScrollView addSubview:imgViewPost];
[scrollimagePostView addSubview:imgViewPost];
x=x+kSCREEN_WIDTH;
if (i < 2) {
innerScrollFrame.origin.x += innerScrollFrame.size.width;
}
}
scrollimagePostView.contentSize = CGSizeMake(x, scrollimagePostView.frame.size.height );
scrollimagePostView.backgroundColor = [UIColor blackColor];
[self.view addSubview:scrollimagePostView];
[scrollimagePostView setContentOffset:CGPointMake(scrollimagePostView.frame.size.width*(imageTag-1), 0.0f) animated:NO];
btnCloseFullIMageView = [[UIButton alloc]initWithFrame:CGRectMake(kSCREEN_WIDTH-80, 25, 70, 25)];
[btnCloseFullIMageView setTitle:#"Close" forState:UIControlStateNormal];
[btnCloseFullIMageView setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btnCloseFullIMageView.backgroundColor = [UIColor blackColor];
btnCloseFullIMageView.layer.borderColor = [UIColor whiteColor].CGColor;
btnCloseFullIMageView.layer.borderWidth = 0.5;
btnCloseFullIMageView.layer.cornerRadius = 3.0;
btnCloseFullIMageView.clipsToBounds = TRUE;
[btnCloseFullIMageView addTarget:self action:#selector(closeFullImageView:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnCloseFullIMageView];
}

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.

Loading overlay on collection view

I have a loading view that I insert over the top of a view while it is parsing data from the internet using a separate thread, in this case its on top of a UICollectionView.
For some reason that I cannot understand the loading overlay disappears on its own whist the parsing is still taking place, presenting a blank screen for a second or two. It doesn't seem to happen on UITableViews just on UIcollectionviews. Any help would be appreciated.
Activity overlay.m:
#import "ActivityOverlayController.h
#interface ActivityOverlayController ()
#end
#implementation ActivityOverlayController
-(id)initWithFrame:(CGRect)theFrame {
if (self = [super init]) {
frame = theFrame;
self.view.frame = theFrame;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"%#", #"ActivityOverlayController called");
container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 110, 30)];
activityLabel = [[UILabel alloc] init];
activityLabel.text = NSLocalizedString(#"Loading", #"string1");
activityLabel.textColor = [UIColor lightGrayColor];
activityLabel.font = [UIFont boldSystemFontOfSize:17];
[container addSubview:activityLabel];
activityLabel.frame = CGRectMake(0, 3, 70, 25);
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.color = [UIColor blackColor];
activityIndicator.hidesWhenStopped = TRUE;
[activityIndicator startAnimating];
activityIndicator.frame = CGRectMake(80, 0, 30, 30);
[container addSubview:activityIndicator];
[self.view addSubview:container];
container.center = CGPointMake(frame.size.width/2, frame.size.height/2);
self.view.backgroundColor = [UIColor colorWithRed:255 green:255 blue:255 alpha:0.7];
}
-(void)viewWillAppear:(BOOL) animated {
[super viewWillAppear:animated];
}
-(void)viewWillDisappear:(BOOL) animated {
[super viewWillDisappear:animated];
}
-(void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[activityIndicator stopAnimating];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#end
Parsing part of collectionViewController.m:
-(void)ParseCollectionView{
[self performSelectorOnMainThread:#selector(showActivityView) withObject:nil waitUntilDone:YES];
CollectionViewImages = [[NSMutableArray alloc]init];
NSData *xmlData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:GalleryTitle]];
cvTBXML = [[TBXML alloc]initWithXMLData:xmlData];
// Obtain root element
TBXMLElement * root = cvTBXML.rootXMLElement;
TBXMLElement * channel = [TBXML childElementNamed:#"channel" parentElement:root];
if (root)
{
TBXMLElement * item = [TBXML childElementNamed:#"item" parentElement:channel];
while (item !=nil)
{
//create new instance of news object
NSObject *Imagetoparse = [[GalleryImage alloc] init];
TBXMLElement * link = [TBXML childElementNamed:#"link" parentElement:item];
NSString *linktext= [TBXML textForElement:link];
[Imagetoparse setValue:linktext forKey:#"link"];
TBXMLElement * thumbnail = [TBXML childElementNamed:#"description" parentElement:item];
NSString *Thumbnailtext= [TBXML textForElement:thumbnail];
Thumbnailtext = [Thumbnailtext substringFromIndex:21];
NSInteger *slength = Thumbnailtext.length -4;
Thumbnailtext = [Thumbnailtext substringToIndex:slength];
Thumbnailtext = [Thumbnailtext stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
Thumbnailtext = [Thumbnailtext stringByReplacingOccurrencesOfString:#"thumb" withString:#"main"];
NSLog(#"Thumnail1 : %#", Thumbnailtext);
NSData *Thumbnailimage = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: Thumbnailtext]];
[Imagetoparse setValue:Thumbnailimage forKey:#"thumbnail"];
[CollectionViewImages addObject:Imagetoparse];
item = [TBXML nextSiblingNamed:#"item" searchFromElement:item];
}
}
[self.collectionView reloadData];
NSLog(#"%#", #"Finished Parse Collection View");
[self performSelectorOnMainThread:#selector(hideActivityView) withObject:nil waitUntilDone:NO];
}
-(void)showActivityView {
if (overlayController == nil) {
overlayController = [[ActivityOverlayController alloc] initWithFrame:(self.view.superview.bounds)];
}
[self.view.superview insertSubview:overlayController.view aboveSubview:self.view];
}
-(void)hideActivityView {
[overlayController.view removeFromSuperview];
}

Horizontal scrolling on a view in ios [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
How can I implement scroll view to horizontally scroll the view pages loaded from a NSDictionary. Presently i am using swipegesture but that is little slow.
What code should I implement to achieve horizontal scrolling?
i am using this code:
-(void)DownLoadData:(NSString *)indexSelect
{
{
[[SharedUtilities getInstance]AddActivityIndicatorViewOnMainThread:self.view];
}
self._parserForNewsDetail = [afaqsParser getInstance];
[[afaqsParser getInstance] setCacheNeed:TRUE];
[self._parserForNewsDetail parseWithUrl:[_arrUrlLinks objectAtIndex:[indexSelect integerValue]] UrlTypefor:nil];
NSDictionary *resultDic;
resultDic = [[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0];
NSLog(#"Detail Dic = %#",[resultDic description]);
if (resultDic== NULL || resultDic ==nil)
{
//Check internet here
[[SharedUtilities getInstance]RemoveActivityIndicatorView];
[SharedUtilities ShowAlert:#"No Data Found" title:nil withView:self.view];
return;
}
[self performSelectorOnMainThread:#selector(SetValuesInUserInterface:) withObject: resultDic waitUntilDone:NO];
[[SharedUtilities getInstance]RemoveActivityIndicatorView];
}
-(void)SetValuesInUserInterface:(NSDictionary *)Dic
{
self._imageView1.layer.cornerRadius = 4;
self._imageView1.clipsToBounds = YES;
self._imageView1.tag = 999;
NSURL *imgurl =[NSURL URLWithString:[[Dic valueForKey:#"image"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
self._imageView1.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:imgurl]];
NSArray *subviewsArr = [self.view subviews];
for (int i=0; i<[subviewsArr count]; i++) {
if ([[subviewsArr objectAtIndex:i] isKindOfClass:[ImageDownLoader class]]) {
[[subviewsArr objectAtIndex:i] removeFromSuperview];
}
}
if ([[Dic valueForKey:#"image"] isEqual:#""])
{
// strg=[NSString stringWithFormat:#"%#, ",[Dic valueForKey:#"image"]];
_imageView1.hidden=YES;
// _txtView.frame=CGRectMake(4.0f,95.0f,310.0f,100.0f );
_txtView.frame=CGRectMake(4.0f,95.0f,_txtView.frame.size.width,_txtView.frame.size.height );
NSLog(#"NO IMAGE");
}
else{
_imageView1.hidden=NO;
_imageView1.frame=CGRectMake(4.0f,95.0f,310.0f,180.0f );
_txtView.frame=CGRectMake(4.0f,316.0f,_txtView.frame.size.width,_txtView.frame.size.height );
NSLog(#"IMAGE VISIBLE");
}
self._scrollView.scrollEnabled = YES;
self._scrollView.showsVerticalScrollIndicator = YES;
self._scrollView.showsHorizontalScrollIndicator = YES;
self._header.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:18];
[self._header setText: [Dic valueForKey:#"header"]];
self._header.textColor=[UIColor blackColor];
[self._publicationDate setText:[Dic valueForKey:#"PUB_DATE"]];
[self._kicker setText:[Dic valueForKey:#"kicker"]];
[self._txtView setText:[Dic valueForKey:#"ARTICLE_BODY"]];
NSString *writer;
if ([[Dic valueForKey:#"AUTHOR"] length]>2)
{
writer=[NSString stringWithFormat:#"%#, ",[Dic valueForKey:#"AUTHOR"]];
}
else
{
writer=#"";
}
NSString *city;
if ([[Dic valueForKey:#"REPORTING_CITY"] length]>2)
{
city=[NSString stringWithFormat:#", %#",[Dic valueForKey:#"REPORTING_CITY"]];
}
else
{
city=#"";
}
NSString *str = [NSString stringWithFormat:#"%#ee%#", writer,city];
//[cell._Writer setText: [tempDic valueForKey:#"writer"]];
[self._Writer setText:str];
[_txtView sizeToFit]; //added
[_txtView layoutIfNeeded]; //added
CGRect frame = self._txtView.frame;
self._txtView.frame = frame;
[_txtView setScrollEnabled:NO];
self._scrollView.contentSize = CGSizeMake(320,440+frame.size.height);
_titleLabel.frame= CGRectMake(0, self._scrollView.contentSize.height-119, [[UIScreen mainScreen] bounds].size.width, 40);
_titleLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:1];
_titleLabel.textColor = [UIColor whiteColor];
_titleLabel.textAlignment = NSTextAlignmentCenter;
_titleLabel.font = [UIFont fontWithName:#"Helvetica" size:13.5];
_titleLabel.numberOfLines=2;
[self._scrollView addSubview:_titleLabel];
}
-(void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_titleLabel = [[UILabel alloc] init];
lblTitle.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:20];
lblTitle.text=_strTitle;
NSLog(#"arrUrls %d",[_arrUrlLinks count]);
NSLog(#"strCurrentNewsSelect %#",_strCurrentNewsSelect);
[[NSNotificationCenter defaultCenter]
postNotificationName:#"DISABLEGESTURE"
object:self];
count=[_strCurrentNewsSelect integerValue];
[self performSelectorInBackground:#selector(DownLoadData:) withObject:_strCurrentNewsSelect];
if([_strCurrentNewsSelect isEqualToString:#"0"])
{
btnPreviousNews.userInteractionEnabled=FALSE;
}
else{
}
_lblNewsCount.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:16];
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",[_strCurrentNewsSelect integerValue]+1,[_arrUrlLinks count]];
// Do any additional setup after loading the view from its nib.
UIButton *shareBtn = [[UIButton alloc]initWithFrame:CGRectMake(280, 340, 40, 40)];
[shareBtn addTarget:self action:#selector(Share:) forControlEvents:UIControlEventTouchUpInside];
[shareBtn setBackgroundImage:[UIImage imageNamed:#"share1.png"] forState:UIControlStateNormal];
// [self.view addSubview:shareBtn];
if([_strCurrentNewsSelect isEqualToString:#"0"])
{
btnPreviousNews.userInteractionEnabled=FALSE;
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow2_prev.png"] forState:UIControlStateNormal];
}
if([_strCurrentNewsSelect isEqualToString:[NSString stringWithFormat:#"%d",[_arrUrlLinks count]-1]])
{
btnNextNews.userInteractionEnabled=FALSE;
[btnNextNews setImage:[UIImage imageNamed:#"arrow2_next.png"] forState:UIControlStateNormal];
}
UISwipeGestureRecognizer *rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(rightSwipeHandle:)];
rightRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
[rightRecognizer setNumberOfTouchesRequired:1];
//add the your gestureRecognizer , where to detect the touch..
[_scrollView addGestureRecognizer:rightRecognizer];
UISwipeGestureRecognizer *leftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(leftSwipeHandle:)];
leftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[leftRecognizer setNumberOfTouchesRequired:1];
[_scrollView addGestureRecognizer:leftRecognizer];
}
- (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
[self btnPreviousClick];
}
- (void)leftSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
NSLog(#"leftSwipeHandle");
[self btnNextClick];
}
-(IBAction)Share:(UIButton *)sender
{
NSLog(#"SHare called =%d",sender.tag);
// NSDictionary *tempDic = [[self._resultDic valueForKey:#"items"] objectAtIndex:sender.tag];
[[SharedUtilities getInstance] set_LinkForSharing:[[[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0] valueForKey:#"image"]];
[[SharedUtilities getInstance]set_headerForSharing:[[[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0] valueForKey:#"header"]];
[[SharedUtilities getInstance]set_viewController:self];
[[SharedUtilities getInstance]Share];
}
-(IBAction)btnBackPress:(id)sender;
{
[[NSNotificationCenter defaultCenter]
postNotificationName:#"ENABLEGESTURE"
object:self];
[self.navigationController popViewControllerAnimated:YES];
lblTitle.text=_strTitle;
}
-(IBAction)btnNextClick
{
btnPreviousNews.userInteractionEnabled=TRUE;
if(count!=[_arrUrlLinks count] -1)
{
if(count==[_arrUrlLinks count]-2)
{
btnNextNews.userInteractionEnabled=FALSE;
[btnNextNews setImage:[UIImage imageNamed:#"arrow2_next.png"] forState:UIControlStateNormal];
}
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow1_prev.png"] forState:UIControlStateNormal];
count=count +1;
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",count+1,[_arrUrlLinks count]];
NSLog(#"next %d",count);
[self performSelectorInBackground:#selector(DownLoadData:) withObject:[NSString stringWithFormat:#"%d",count]];
}
else{
btnNextNews.userInteractionEnabled=FALSE;
}
}
-(IBAction)btnPreviousClick
{
btnNextNews.userInteractionEnabled=TRUE;
if(count==0)
{
btnPreviousNews.userInteractionEnabled=FALSE;
}
else{
if(count==1)
{
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow2_prev.png"] forState:UIControlStateNormal];
btnPreviousNews.userInteractionEnabled=FALSE;
}
[btnNextNews setImage:[UIImage imageNamed:#"arrow1_next.png"] forState:UIControlStateNormal];
count=count-1;
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",count+1,[_arrUrlLinks count]];
NSLog(#"previous %d",count);
[self performSelectorInBackground:#selector(DownLoadData:) withObject:[NSString stringWithFormat:#"%d",count]];
}
}
}
Have you tried as like below methods,
UIScrollView * _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 10.0, 320.0, 280.0)];
_scrollView.backgroundColor = [UIColor clearColor];
_scrollView.pagingEnabled = YES;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.scrollsToTop = NO;
_scrollView.delegate = self;
[self addSubview:_scrollView];
float width = 0.0;
for (int i = 0; i < pageCount; i++)
{
UIView * yourView = [[UIView alloc] initWithFrame:CGRectMake((i * 320.0) + 20.0, 0.0, 280.0, 280.0);
[_scrollView addSubview:yourView];
width = yourView.frame.size.width + yourView.frame.origin.x + 20.0;
}
[_scrollView setContentSize:CGSizeMake(width, _scrollView.frame.size.height)];
Look at UIScrollView. To be honest this question makes it look like you've done very little research into the problem though. Can you tell us a bit more about what you currently have and what you've done so far?
UIScrollView Scroll depends on the ContentSize. So you have to set the ContentSize.
For Horizinatal Scrolling
[scroll setContentSize:CGSizeMake(1500, scroll.frame.size.height)];

NSMutableArray data sorting by a distance

Have a problem with my MutableArray. I've the data array in my tableview, and everything is ok, but when the data is sorting by a distance and i'm choosing an item in cell, it shows me incorrect data in new viewcontroller. It shows the data without sorting. It's like a broken link) Hope for your help)
i'm new in obj-c, so i apologise)
here is my code:
list = [[NSMutableArray alloc] init];
[list addObject:#{#"name": #"Central office", #"address":#"наб. Обводного канала, д.66А", #"phone":#"+7 (812) 320-56-21 (многоканальный)", #"workTime":#"ПН-ПТ: с 9:30 до 18:30", #"email":#"mail#ibins.ru", #"payment":#"Принимаются к оплате пластиковые карты VISA и MasterCard", #"longitude":#30.336842, #"latitude":#59.913950}];
[list addObject:#{#"name": #"Second office", #"address":#"ул. Камышовая, д.38", #"phone":#"+7 (812) 992-992-6; +7 (812) 456-26-43", #"workTime":#"Ежедневно: с 9:30 до 20:00", #"email":#"sever#ibins.ru", #"payment":#"Принимаются к оплате пластиковые карты VISA и MasterCard", #"longitude":#30.219863, #"latitude":#60.008805}];
[list addObject:#{#"name": #"Third office", #"address":#"Street name", #"phone":#"phone number", #"workTime":#"Work time", #"email":#"email address", #"longitude":#30.294254, #"latitude":#60.028728}];
[self constructList];
[self constructPins];
}
- (IBAction)switchDisplayType:(id)sender {
[UIView beginAnimations:#"View Flip" context:nil];
[UIView setAnimationDuration:0.80];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:NO];
[UIView commitAnimations];
if ([(UISegmentedControl*)sender selectedSegmentIndex] == 1) {
map.hidden = YES;
contentSV.hidden = NO;
}
else {
map.hidden = NO;
contentSV.hidden = YES;
}
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
static NSString* BridgeAnnotationIdentifier = #"bridgeAnnotationIdentifier";
MKPinAnnotationView* customPinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:BridgeAnnotationIdentifier] autorelease];
customPinView.pinColor = MKPinAnnotationColorRed;
customPinView.animatesDrop = YES;
customPinView.canShowCallout = YES;
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
// NSLog(#"%#",rightButton);
[rightButton addTarget:self
action:#selector(annotationButtonTapped:)
forControlEvents:UIControlEventTouchUpInside];
customPinView.rightCalloutAccessoryView = rightButton;
return customPinView;//[kml viewForAnnotation:annotation];
}
- (void)annotationButtonTapped:(id)sender {
DetailVC *sampleVC = [[DetailVC alloc] initWithNibName:#"DetailVC" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:sampleVC animated:YES];
[sampleVC release];
for (NSDictionary *dict in list) {
if ([[dict valueForKey:#"name"] isEqualToString:selectedAnnTitle]) {
[sampleVC updateViewWithDict:dict];
}
}
}
- (void)constructPins {
for (NSDictionary *dict in list) {
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.3;
span.longitudeDelta = 0.3;
CLLocationCoordinate2D location;
location.latitude = [[dict valueForKey:#"latitude"] floatValue];
location.longitude = [[dict valueForKey:#"longitude"] floatValue];
if (location.latitude == 0.0 && location.longitude == 0.0)
return;
region.span = span;
region.center = location;
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = location;
point.title = [dict valueForKey:#"name"];
[map addAnnotation:point];
[map setRegion:region animated:YES];
}
}
- (void)constructList {
int n = 0;
for (NSDictionary *dict in list) {
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0, 100*n, 320, 100)];
container.backgroundColor = [UIColor whiteColor];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
button.tag = n;
[button addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
[container addSubview:button];
NSString *str = [NSString stringWithFormat:#"%#\nAddress: %#\nPhone: %#\nWork Time: %#", [dict valueForKey:#"name"], [dict valueForKey:#"address"], [dict valueForKey:#"phone"], [dict valueForKey:#"workTime"]];
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 80)];
nameLabel.textAlignment = NSTextAlignmentLeft;
nameLabel.numberOfLines = 0;
nameLabel.text = str;
nameLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:12.0];
[container addSubview:nameLabel];
UIView *separator = [[UIView alloc]initWithFrame:CGRectMake(0, 99, 320, 1)];
separator.backgroundColor = [UIColor darkGrayColor];
[container addSubview:separator];
[contentSV addSubview:container];
n++;
contentSV.contentSize = CGSizeMake(0, 100*n);
}
}
- (float)distanceBetweenLat1:(float)tlat1 lon1:(float)tlon1 lat2:(float)tlat2 lon2:(float)tlon2 {
float result = 0.0;
int R = 6371;
float currentLatitude = tlat1;
float currentLongtitude = tlon1;
float lat2 = tlat2;
float lon2 = tlon2;
float dLat = (lat2-currentLatitude)*M_PI/180;
float dLon = (lon2-currentLongtitude)*M_PI/180;
float nlLat = currentLatitude*M_PI/180;
lat2 = lat2*M_PI/180;
float a = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(nlLat) * cos(lat2);
float c = 2 * atan2(sqrt(a), sqrt(1-a));
result = R * c;
return result;
}
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
selectedAnnTitle = [view.annotation title];
return;
DetailVC *sampleVC = [[DetailVC alloc] initWithNibName:#"DetailVC" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:sampleVC animated:YES];
NSString *ttl = [view.annotation title];
for (NSDictionary *dict in list) {
if ([[dict valueForKey:#"name"] isEqualToString:ttl]) {
[sampleVC updateViewWithDict:dict];
}
}
[map deselectAnnotation:view.annotation animated:NO];
}
- (void)buttonTapped:(id)sender {
DetailVC *sampleVC = [[DetailVC alloc] initWithNibName:#"DetailVC" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:sampleVC animated:YES];
int n = 0;
for (NSDictionary *dict in list) {
if (n == [sender tag]) {
[sampleVC updateViewWithDict:dict];
}
n++;
}
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
NSLog(#"didUpdateUserLocation");
MKAnnotationView* annotationView = [mapView viewForAnnotation:userLocation];
annotationView.canShowCallout = NO;
if (!userLocationUpdated) {
if (userLocation.coordinate.latitude > 0.1 && userLocation.coordinate.longitude > 0.1) {
// NSLog(#"SORT BY DISTANCE");
userLocationUpdated = YES;
for (int i = 0; i < [list count]; i++) {
NSMutableDictionary *record = [[NSMutableDictionary alloc] initWithDictionary:[list objectAtIndex:i]];
float latitude = [[record valueForKey:#"latitude"] floatValue];
float longitude = [[record valueForKey:#"longitude"] floatValue];
float dist = [self distanceBetweenLat1:map.userLocation.coordinate.latitude lon1:map.userLocation.coordinate.longitude lat2:latitude lon2:longitude];
NSNumber *distN = [NSNumber numberWithFloat:dist];
[record setObject:distN forKey:#"distance"];
[list replaceObjectAtIndex:i withObject:record];
}
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"distance" ascending:YES];
NSArray *itemsListSorted = [[NSArray alloc] initWithArray:list];
itemsListSorted = [itemsListSorted sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
for (UIView *view in contentSV.subviews) {
[view removeFromSuperview];
}
for (int i = 0; i < [itemsListSorted count]; i++) {
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0, 100*i, 320, 100)];
container.backgroundColor = [UIColor whiteColor];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
button.tag = i;
[button addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
[container addSubview:button];
NSString *str = [NSString stringWithFormat:#"%#\nAddress: %#\nPhone: %#\nWorkTime: %#", [[itemsListSorted objectAtIndex:i] valueForKey:#"name"], [[itemsListSorted objectAtIndex:i] valueForKey:#"address"], [[itemsListSorted objectAtIndex:i] valueForKey:#"phone"], [[itemsListSorted objectAtIndex:i] valueForKey:#"workTime"]];
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 80)];
nameLabel.textAlignment = NSTextAlignmentLeft;
nameLabel.numberOfLines = 0;
nameLabel.text = str;
nameLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:12.0];
[container addSubview:nameLabel];
UILabel *distanceLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 2, 300, 21)];
distanceLabel.textAlignment = NSTextAlignmentRight;
distanceLabel.text = [NSString stringWithFormat:#"%.1f км", [[[itemsListSorted objectAtIndex:i] valueForKey:#"distance"] floatValue]];
distanceLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:12.0];
distanceLabel.textColor = [UIColor lightGrayColor];
[container addSubview:distanceLabel];
UIView *separator = [[UIView alloc]initWithFrame:CGRectMake(0, 99, 320, 1)];
separator.backgroundColor = [UIColor darkGrayColor];
[container addSubview:separator];
[contentSV addSubview:container];
contentSV.contentSize = CGSizeMake(0, 100*(i+1));
}
}
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#end
Although there are numerous issues with this code (the least of which are some minor precision issues with the distance calculation), the problem is not with the distance calculation.
The detail view controller shows incorrect data because it is given the data from the list array which is not itself sorted by distance.
In the didUpdateUserLocation delegate method, the contents of list are copied to a local array named itemsListSorted.
Only the itemsListSorted array is sorted by distance and then the display is updated using this local array.
But the original list array (which the buttonTapped method uses as the source of the data to send to the detail view controller) is never updated.
So if "Central Office" is at index 0 in list but gets moved to index 2 in itemsListSorted, the display shows the correct position but when you tap on it, the buttonTapped method sends the item at index 2 from the list array which does not have "Central Office" (it's still at index 0 in list).
One way to fix this problem is to stop using a local array and sort the list array directly.
In didUpdateUserLocation, you could replace these two lines:
NSArray *itemsListSorted = [[NSArray alloc] initWithArray:list];
itemsListSorted = [itemsListSorted sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
with this:
[list sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
and then replace all references to itemsListSorted in the same method with list.
Regarding the other issues with the code, there is not enough room to point them all out or explain them in one answer. However, here are just a few highlights:
Instead of a manually creating a "table view", use an actual UITableView.
Instead of manually calculating distance between coordinates, use the distanceFromLocation method in the CLLocation class or the MKMetersBetweenMapPoints function.
In viewForAnnotation, you should return nil if annotation is of type MKUserLocation otherwise it will appear as a red pin just like the others.
Use ARC instead of manual memory management.

Resources