App freezes and crashes with kernel panic - - ios

I have an app which displays some basic animation triggered by the playback of midi file. It works ok during the first playback but freezes during subsequent playbacks. The device then usually reboots generating a crash log indicating that a kernel panic took place. Occasionally it just hangs without a reboot.
The animation consists of an small png image which has the opacity changed from high to low to give a fading effect.
The freeze takes place on the line :[self performSelectorOnMainThread:#selector( setPitch: ) withObject:[NSNumber numberWithInteger:[note intValue]] waitUntilDone:YES];
Here is the method which contains this line:
- (void)log:(NSNotification *)notification {
[NSThread isMainThread];
NSDictionary* info = notification.userInfo;
NSNumber *note;
note = [info objectForKey:kNAMIDI_Note];
BRMidiNoteName *noteConverter = [[BRMidiNoteName alloc] init];
NSString *noteName;
noteName = [noteConverter nameFromNumber:[note intValue] withNotation:[defaults valueForKey:kSettingsNotation]];
[self.currentNoteLabel performSelectorOnMainThread: #selector( setText: ) withObject: noteName waitUntilDone: YES];
[self performSelectorOnMainThread:#selector( setPitch: ) withObject:[NSNumber numberWithInteger:[note intValue]] waitUntilDone:YES];
}
-(void) setPitch:(NSNumber*) pitchValue{
NSInteger visualPitchValue = [pitchValue intValue]- [_currentTrack.trackStartNote intValue] - voiceTransposeValue + 1;
if ([defaults boolForKey:kSettingsVisualiser]) {
//UIImageView *img = [[UIImageView alloc]init];
UIImageView *img;
if ((visualPitchValue > 0 )) {
// highlight new pitch
img = (UIImageView *)[self.view viewWithTag:visualPitchValue];
if (([pitchValue integerValue] < [currentVoice.bridgeLow integerValue])) {
[img setImage:[UIImage imageNamed:#"bar_green.png"]];
}
else if (([pitchValue integerValue] <= [currentVoice.bridgeHigh integerValue])) {
[img setImage:[UIImage imageNamed:#"bar_orange"]];
}
else{
[img setImage:[UIImage imageNamed:#"bar_blue.png"]];
}
[img setAlpha:1.0];
// Set up fade out effect
CABasicAnimation *fadeOutAnimation = [CABasicAnimation animationWithKeyPath:#"opacity"];
[fadeOutAnimation setToValue:[NSNumber numberWithFloat:_fadeToOpacity]];
fadeOutAnimation.fillMode = kCAFillModeForwards;
fadeOutAnimation.removedOnCompletion = NO;
CAAnimationGroup *group = [CAAnimationGroup animation];
group.fillMode = kCAFillModeForwards;
group.removedOnCompletion = NO;
// [group setAnimations:[NSArray arrayWithObjects:fadeOutAnimation, pathAnimation, nil]];
[group setAnimations:[NSArray arrayWithObjects:fadeOutAnimation, nil]];
group.duration = 0.7f;
group.delegate = self;
[group setValue:img forKey:#"imageViewBeingAnimated"];
[img.layer addAnimation:group forKey:#"savingAnimation"];
}
}
}

I found that changing the waitUntilDone from YES to NO stopped the device screen from freezing.
[self.currentNoteLabel performSelectorOnMainThread: #selector( setText: ) withObject: noteName waitUntilDone: NO];
[self performSelectorOnMainThread:#selector( setPitch: ) withObject:[NSNumber numberWithInteger:[note intValue]] waitUntilDone:NO];

Related

Why is this animation not working as intended?

Hi there all the past couple days now I’ve been trying to modify the iOS tweak Daisy. I have successfully added more fonts, make the Hello animation stay on the screen and merged a closed pull request that the original dev didn’t want In. Anyways I’m up to trying to fix this bug that the original version has and that is that the “playHelloStartAnimation” will bug out sometimes when waking the phone. Sometimes it will fully replay the animation from the beginning or a couple frames from the middle of the animation, other times it will finish and show nothing for a few millisecond and then continue to the next animation or will play as intended. Tried adding a blank animation to play first so when it dose bug out you’ll won’t see but didn’t help, change times, tried other hooks still happens. Can’t figure out why any help would be appreciated.
%group DiaryHello
%hook CSCoverSheetView
%property(nonatomic, retain)UIView* diaryHelloIconView;
%property(nonatomic, retain)UILabel* diaryHelloLabel;
- (void)didMoveToWindow { // add iphone hello
%orig;
// hello label
if (enableHelloSwitch && showHelloGreetingSwitch && ![self diaryHelloLabel]) {
self.diaryHelloLabel = [UILabel new];
[[self diaryHelloLabel] setTextColor:[UIColor whiteColor]];
if ([fontFamilyValue intValue] == 0) [[self diaryHelloLabel] setFont:[UIFont fontWithName:#"Selawik-Regular" size:24]];
else if ([fontFamilyValue intValue] == 1) [[self diaryHelloLabel] setFont:[UIFont systemFontOfSize:24 weight:UIFontWeightRegular]];
[[self diaryHelloLabel] setText:greetingValue];
[[self diaryHelloLabel] setTextAlignment:NSTextAlignmentCenter];
[[self diaryHelloLabel] setAlpha:0];
[[self diaryHelloLabel] setHidden:YES];
[self addSubview:[self diaryHelloLabel]];
[[self diaryHelloLabel] setTranslatesAutoresizingMaskIntoConstraints:NO];
[NSLayoutConstraint activateConstraints:#[
[self.diaryHelloLabel.topAnchor constraintEqualToAnchor:self.topAnchor constant:150],
[self.diaryHelloLabel.leadingAnchor constraintEqualToAnchor:self.leadingAnchor],
[self.diaryHelloLabel.trailingAnchor constraintEqualToAnchor:self.trailingAnchor],
]];
}
}
%new
- (void)initHelloViewWithAnimation:(int)animation { // set hello view up
if (!enableHelloSwitch) return;
if (enableMediaPlayerSwitch && ![[self diaryPlayerView] isHidden]) return;
[[self diaryHelloIconView] stopAnimating];
[[self diaryHelloIconView] removeFromSuperview];
self.diaryHelloIconView = nil;
if (animation == 0) {
helloStartArray = [NSMutableArray new];
for (int i = 0; i < 24; i++) [helloStartArray addObject:[UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"/Library/PreferenceBundles/DiaryPreferences.bundle/hello/start/%i.png", i]]];
helloStartImage = [UIImage animatedImageWithImages:helloStartArray duration:0.6];
self.diaryHelloIconView = [[UIImageView alloc] initWithImage:helloStartImage];
helloSearchingArray = nil;
helloSearchingImage = nil;
helloAuthenticatedArray = nil;
helloAuthenticatedImage = nil;
} else if (animation == 1) {
helloSearchingArray = [NSMutableArray new];
for (int i = 0; i < 116; i++) [helloSearchingArray addObject:[UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"/Library/PreferenceBundles/DiaryPreferences.bundle/hello/searching/%i.png", i]]];
helloSearchingImage = [UIImage animatedImageWithImages:helloSearchingArray duration:4.28];
self.diaryHelloIconView = [[UIImageView alloc] initWithImage:helloSearchingImage];
helloStartArray = nil;
helloStartImage = nil;
helloAuthenticatedArray = nil;
helloAuthenticatedImage = nil;
} else if (animation == 2) {
helloAuthenticatedArray = [NSMutableArray new];
for (int i = 0; i < 51; i++) [helloAuthenticatedArray addObject:[UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"/Library/PreferenceBundles/DiaryPreferences.bundle/hello/authenticated/%i.png", i]]];
helloAuthenticatedImage = [UIImage animatedImageWithImages:helloAuthenticatedArray duration:1.12];
self.diaryHelloIconView = [[UIImageView alloc] initWithImage:helloAuthenticatedImage];
helloStartArray = nil;
helloStartImage = nil;
helloSearchingArray = nil;
helloSearchingImage = nil;
}
[[self diaryHelloIconView] setContentMode:UIViewContentModeScaleAspectFit];
[[self diaryHelloIconView] setClipsToBounds:YES];
[[self diaryHelloIconView] setHidden:NO];
if (![[self diaryHelloIconView] isDescendantOfView:self]) [self addSubview:[self diaryHelloIconView]];
[[self diaryHelloIconView] setTranslatesAutoresizingMaskIntoConstraints:NO];
[NSLayoutConstraint activateConstraints:#[
[self.diaryHelloIconView.topAnchor constraintEqualToAnchor:self.topAnchor constant:50],
[self.diaryHelloIconView.centerXAnchor constraintEqualToAnchor:self.centerXAnchor],
[self.diaryHelloIconView.heightAnchor constraintEqualToConstant:80],
[self.diaryHelloIconView.widthAnchor constraintEqualToConstant:80],
]];
}
%new
- (void)playHelloStartAnimation { // play hello start animation
if (!enableHelloSwitch) return;
if (enableMediaPlayerSwitch && ![[self diaryPlayerView] isHidden]) return;
shouldPlaySearchAnimation = YES;
[self initHelloViewWithAnimation:0];
[[self diaryHelloIconView] setAnimationRepeatCount:1];
[[self diaryHelloIconView] startAnimating];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[self playHelloSearchingAnimation];
});
}
%new
- (void)playHelloSearchingAnimation { // play hello searching animation
if (!enableHelloSwitch) return;
if (enableMediaPlayerSwitch && ![[self diaryPlayerView] isHidden]) return;
if (!shouldPlaySearchAnimation) return;
[self initHelloViewWithAnimation:1];
[[self diaryHelloIconView] setAnimationRepeatCount:0];
[[self diaryHelloIconView] startAnimating];
if (showHelloGreetingSwitch) [[self diaryHelloLabel] setAlpha:0];
}
%new
- (void)playHelloAuthenticatedAnimation { // play hello authenticated animation
if (!enableHelloSwitch) return;
if (enableMediaPlayerSwitch && ![[self diaryPlayerView] isHidden]) return;
shouldPlaySearchAnimation = NO;
[self initHelloViewWithAnimation:2];
[[self diaryHelloIconView] setAnimationRepeatCount:1];
[[self diaryHelloIconView] startAnimating];
if (showHelloGreetingSwitch) {
NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];
[UIView animateWithDuration:0.25 delay:0.4 options:UIViewAnimationOptionCurveEaseInOut animations:^{
[[self diaryHelloLabel] setHidden:NO];
[[self diaryHelloLabel] setAlpha:1];
[notificationCenter postNotificationName:#"diaryUpdateNotificationList" object:nil];
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
[[self diaryHelloLabel] setAlpha:0];
} completion:^(BOOL finished) {
[[self diaryHelloIconView] setHidden:YES];
[[self diaryHelloLabel] setHidden:YES];
[[self diaryHelloIconView] removeFromSuperview];
[notificationCenter postNotificationName:#"diaryUpdateNotificationList" object:nil];
}];
}];
} else {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.8 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[[self diaryHelloIconView] setHidden:YES];
[[self diaryHelloIconView] removeFromSuperview];
[[NSNotificationCenter defaultCenter] postNotificationName:#"diaryUpdateNotificationList" object:nil];
});
}
}
%end
%hook CSCoverSheetViewController
- (void)viewDidDisappear:(BOOL)animated { // remove hello view when lock screen disappeared
%orig;
// free up memory when hello is not visible
[[coverSheetView diaryHelloIconView] stopAnimating];
[[coverSheetView diaryHelloIconView] removeFromSuperview];
helloStartArray = nil;
helloStartImage = nil;
helloSearchingArray = nil;
helloSearchingImage = nil;
helloAuthenticatedArray = nil;
helloAuthenticatedImage = nil;
}
%end
%hook SBLockScreenManager
- (void)lockUIFromSource:(int)arg1 withOptions:(id)arg2 { // remove hello view when device was locked
%orig;
// free up memory when hello is not visible
isLockedHello = YES;
isScreenOnHello = NO;
[[coverSheetView diaryHelloIconView] stopAnimating];
[[coverSheetView diaryHelloIconView] removeFromSuperview];
helloStartArray = nil;
helloStartImage = nil;
helloSearchingArray = nil;
helloSearchingImage = nil;
helloAuthenticatedArray = nil;
helloAuthenticatedImage = nil;
}
%end
%hook SBBacklightController
- (void)turnOnScreenFullyWithBacklightSource:(long long)arg1 { // update diary when screen turns on
%orig;
if (![[%c(SBLockScreenManager) sharedInstance] isLockScreenVisible]) return; // this method gets called not only when the screen gets turned on, so i verify that it was turned on by checking if the lock screen is visible
if (!isScreenOnHello) [coverSheetView playHelloStartAnimation];
[[NSNotificationCenter defaultCenter] postNotificationName:#"diaryUpdateNotificationList" object:nil];
isScreenOnHello = YES;
}
%end
%hook SBDashBoardBiometricUnlockController
- (void)setAuthenticated:(BOOL)arg1 { // play authenticated animation when unlocked with biometrics
%orig;
if (arg1 && isLockedHello) {
isLockedHello = NO;
[coverSheetView playHelloAuthenticatedAnimation];
}
}
%end
%end
Original tweaks source code: https://github.com/schneelittchen/Diary

How to hide image view in ios?

I have image view, if click button talking tom cat will play with animationRepeatCount:2, after this, I want to hide image view. How to hide that image view?
- (IBAction)catBlinkButton:(UIButton *)sender {
self.imageView.hidden = NO;
self.imageView.animationDuration = 2;
self.imageView.animationRepeatCount = 2;
self.imageView.animationImages = [[NSArray alloc]initWithObjects:
[UIImage imageNamed:#"cat_blink0000.png"],
[UIImage imageNamed:#"cat_blink0001.png"],
[UIImage imageNamed:#"cat_blink0002.png"],
nil];
[self.imageView startAnimating];
}
This is my code...
You can simply use CATransaction like:
self.imageView.hidden = NO;
[CATransaction begin];
[CATransaction setCompletionBlock:^{
self.imageView.hidden = YES;
}];
self.imageView.animationDuration = 2;
self.imageView.animationRepeatCount = 2;
self.imageView.animationImages = [[NSArray alloc]initWithObjects:
[UIImage imageNamed:#"cat_blink0000.png"],
[UIImage imageNamed:#"cat_blink0001.png"],
[UIImage imageNamed:#"cat_blink0002.png"],
nil];
[self.imageView startAnimating];
[CATransaction commit];
CATransaction will dynamically wait for the animation to finish...
You can execute the code after slate on main thread.
- (IBAction)catBlinkButton:(UIButton *)sender {
self.imageView.hidden = NO;
self.imageView.animationDuration = 2;
self.imageView.animationRepeatCount = 2;
self.imageView.animationImages = [[NSArray alloc]initWithObjects:
[UIImage imageNamed:#"cat_blink0000.png"],
[UIImage imageNamed:#"cat_blink0001.png"],
[UIImage imageNamed:#"cat_blink0002.png"],
nil];
[self.imageView startAnimating];
// after 2 seconds.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
// hide imageview
self.imageView.hidden = YES;
});
}
You can do it with UIView's hidden property.
imageView.hidden = true;
- (IBAction)catBlinkButton:(UIButton *)sender {
self.imageView.hidden = NO;
self.imageView.animationDuration = 2;
self.imageView.animationRepeatCount = 2;
self.imageView.animationImages = [[NSArray alloc]initWithObjects:
[UIImage imageNamed:#"cat_blink0000.png"],
[UIImage imageNamed:#"cat_blink0001.png"],
[UIImage imageNamed:#"cat_blink0002.png"],
nil];
[self.imageView startAnimating];
}

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

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

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

Avsession gives "Memory warning "

I am using Avsession to capture images .
while i capture first image i will redirect user to apply effects on it and then get back to my capture image screen and i will preview image on cam capture screen .Then i will allow user to capture 3 more images and i will preview all images on cam capture screen. while i capturing my third image i will receive memory warning.
After Capturing Every image i will crop image to resize.
I have write below code in viewdidload
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
[device setTorchMode:cameraFlashMode];
[device unlockForConfiguration];
[self.btnFlashLight setHidden:NO];
}
else
[self.btnFlashLight setHidden:YES];
cameraMode = AVCaptureDevicePositionBack;
firstImage.layer.borderWidth = 2.0f;
firstImage.layer.borderColor = [UIColor grayColor].CGColor;
secondImage.layer.borderWidth = 2.0f;
secondImage.layer.borderColor = [UIColor grayColor].CGColor;
thirdImage.layer.borderWidth = 2.0f;
thirdImage.layer.borderColor = [UIColor grayColor].CGColor;
forthImage.layer.borderWidth = 2.0f;
forthImage.layer.borderColor = [UIColor grayColor].CGColor;
if ([capturedImages count] == 0)
[self.btnNext setEnabled:NO];
if ([self captureManager] == nil) {
CamCaptureManager *manager = [[CamCaptureManager alloc] init];
[self setCaptureManager:manager];
[[self captureManager] setDelegate:self];
if ([[self captureManager] setupSession]) {
// Create video preview layer and add it to the UI
newCaptureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:[[self captureManager] session]];
UIView *view = [self videoPreviewView];
CALayer *viewLayer = [view layer];
[viewLayer setMasksToBounds:YES];
CGRect bounds = [view bounds];
[newCaptureVideoPreviewLayer setFrame:bounds];
[newCaptureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[viewLayer insertSublayer:newCaptureVideoPreviewLayer below:[[viewLayer sublayers] objectAtIndex:0]];
UIBezierPath *fullScreenPath = [UIBezierPath bezierPathWithRect:view.bounds];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
[fullScreenPath appendPath:[UIBezierPath bezierPathWithRoundedRect:[GeneralDeclaration generalDeclaration].cameraMaskFrame byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(0.0f, 0.0f)]];
maskLayer.fillRule = kCAFillRuleEvenOdd;
maskLayer.path = fullScreenPath.CGPath;
maskLayer.fillColor = [UIColor blackColor].CGColor;
maskLayer.opacity = 0.6f;
maskLayer.lineWidth = 1.0f;
maskLayer.strokeColor = [UIColor whiteColor].CGColor;
[viewLayer insertSublayer:maskLayer above:[[viewLayer sublayers] objectAtIndex:0]];
[self setCaptureVideoPreviewLayer:newCaptureVideoPreviewLayer];
[[self captureManager] session ].sessionPreset = AVCaptureSessionPresetPhoto;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[[self captureManager] session] startRunning];
});
}
}
I have written Below code to process captured Image:
[[self captureManager] captureStillImage];
UIView *flashView = [[UIView alloc] initWithFrame:[[self videoPreviewView] frame]];
[flashView setBackgroundColor:[UIColor whiteColor]];
[[[self view] window] addSubview:flashView];
[UIView animateWithDuration:.4f
animations:^{
[flashView setAlpha:0.f];
}
completion:^(BOOL finished){
[flashView removeFromSuperview];
}
];
firstImage.image = nil;
secondImage.image = nil;
thirdImage.image = nil;
forthImage.image = nil;
//firstImage.userInteractionEnabled = YES;
secondImage.userInteractionEnabled = YES;
thirdImage.userInteractionEnabled = YES;
forthImage.userInteractionEnabled = YES;
for (UIImageView *subview in [firstImage subviews]) {
[subview removeFromSuperview];
}
for (UIImageView *subview in [secondImage subviews]) {
[subview removeFromSuperview];
}
for (UIImageView *subview in [thirdImage subviews]) {
[subview removeFromSuperview];
}
for (UIImageView *subview in [forthImage subviews]) {
[subview removeFromSuperview];
}
for(int i = 0; i < [capturedImages count]; i++)
{
UIImage *removeImage = [UIImage imageNamed:#"remove_image.png"];
UIImageView *removeImageView = [[UIImageView alloc] initWithImage:removeImage];
removeImageView.tag = i;
[removeImageView setCenter:CGPointMake(firstImage.bounds.size.width/2, firstImage.bounds.size.height/2)];
UITapGestureRecognizer *removeImageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(removeImage_Tapped:)];
removeImageTap.numberOfTapsRequired = 1;
removeImageView.userInteractionEnabled = YES;
[removeImageView addGestureRecognizer:removeImageTap];
switch (i) {
case 0:
firstImage.image = [capturedImages objectAtIndex:i];
//[firstImage addSubview:removeImageView];
break;
case 1:
secondImage.image = [capturedImages objectAtIndex:i];
[secondImage addSubview:removeImageView];
break;
case 2:
thirdImage.image = [capturedImages objectAtIndex:i];
[thirdImage addSubview:removeImageView];
break;
case 3:
forthImage.image = [capturedImages objectAtIndex:i];
[forthImage addSubview:removeImageView];
break;
default:
break;
}
}
Please help me to solve.
Set property sessionPreset like this:
[yourcamera session].sessionPreset = AVCaptureSessionPresetHigh
This will not totally remove memory warning but may help to reduce it.

Resources