display the images and audio - ios

I am developing an app.I have a problem while developing the app.
The problem is:
I have a UIImageView and audio.I have 20 images in an array .so i need to display the 20 images in this UIImageView within time interval.Along with the image i need to set the audio.I need to view in same time, ie 20 images and audio should come at same time.
my code as below.
alphabetsStoreArray = [[NSMutableArray alloc]initWithObjects:#"a.png",#"b.png",#"c.png",#"d.png",#"e.png",#"f.png",#"g.png",#"h.png",#"i.png",#"j.png",#"k.png",#"l.png",#"m.png",#"n.png",#"o.png",#"p.png",#"q.png",#"r.png",#"s.png",#"t.png",#"u.png",#"v.png",#"w.png",#"x.png",#"y.png",#"z.png", nil];
commonFunctionObject = [[SpeechCommonFunctions alloc]init];
commonFunctionObject.isRecordComplete = NO;
counter = 0;
isMicPresent = YES;
_confirmationPopupView.hidden = true;
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(repeatActionFire) userInfo:nil repeats:NO];
// Do any additional setup after loading the view.
}
-(void)repeatActionFire
{
if(counter >= alphabetsStoreArray.count)
{
NSLog(#"finished");
[_alphabetsShowImageView removeFromSuperview];
[_speakerOrMicImageView removeFromSuperview];
UIImageView *congratzView = [[UIImageView alloc]initWithFrame:self.view.frame];
congratzView.image = [UIImage imageNamed:#"congratulation.png"];
[self.view addSubview:congratzView];
[self performSelector:#selector(navNew) withObject:nil afterDelay:3];
}
else
{
[commonFunctionObject textToSpeechAction:alphabetsStoreArray :counter :_alphabetsShowImageView :_speakerOrMicImageView :isMicPresent];
[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(ActionToCkeckRecordCompletion) userInfo:nil repeats:YES];
}
}
-(void)ActionToCkeckRecordCompletion
{
if(commonFunctionObject.isRecordComplete)
{
_confirmationPopupView.hidden = false;
}
}
-(void)navNew
{
v11=[self.storyboard instantiateViewControllerWithIdentifier:#"maincontroller"];
[self presentViewController:v11 animated:NO completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
} */
-(IBAction)homebut:(id)sender{
UIAlertController * alert=[UIAlertController alertControllerWithTitle:#"Title"
message:#"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* Home = [UIAlertAction
actionWithTitle:#"RETURN TO HOME"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
v11=[self.storyboard instantiateViewControllerWithIdentifier:#"maincontroller"];
[self presentViewController:v11 animated:NO completion:nil];
}];
UIAlertAction* Cancel = [UIAlertAction
actionWithTitle:#"CANCEL"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
}];
[alert addAction:Cancel];
[alert addAction:Home];
[self presentViewController:alert animated:YES completion:nil];
}
- (IBAction)playButtonAction:(id)sender
{
[commonFunctionObject recordPlayAction];
}
- (IBAction)nextButtonAction:(id)sender
{
counter+=1;
_confirmationPopupView.hidden = true;
commonFunctionObject.isRecordComplete = NO;
if(commonFunctionObject.player.playing){[commonFunctionObject.player stop];}
[self repeatActionFire];
}
- (IBAction)retryButtonAction:(id)sender
{
_confirmationPopupView.hidden = true;
commonFunctionObject.isRecordComplete = NO;
if(commonFunctionObject.player.playing){[commonFunctionObject.player stop];}
[self repeatActionFire];
}
how to do?

Try this, May be you need more than this, but here is a start to get you in the right direction.
-(IBAction)btnclicked:(id)sender {
NSMutableArray *images = [[NSMutableArray alloc]init];
//all alloc does is allocate memory. The -init method is crucial to
actually initialize the object into a working state.
for (int imagenumber = 1; imagenumber <= 45; imagenumber++) {
NSMutableString *myString = [NSMutableString stringWithFormat:#"%i.png", imagenumber];
[images addObject:[UIImage imageNamed:myString]];
}
CGRect frame = CGRectMake(0.0, 0.0, 320, 460);
UIImageView *imageview = [[UIImageView alloc] initWithFrame:frame];
imageview.contentMode = UIViewContentModeScaleToFill;
NSURL *url = [NSURL fileURLWithPath:[NSString
stringWithFormat:#"%#/giggity stick around.wav", [[NSBundle mainBundle]
resourcePath]]];
soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url
error:nil];
soundPlayer.volume = 1;
[soundPlayer play];
imageview.animationImages = images;
imageview.animationDuration = 3.2;
imageview.animationRepeatCount = 1;
[imageview startAnimating];
[self.view addSubview:imageview];
}
Use the AVFoundation to play the audio.

Related

Async call causing EXC_BAD_INSTRUCTION crash

The app I'm working on is using a function that is working fine but blocks the main thread. I am attempting to add a loading spinner using SVProgressHUD and that requires I call my function asynchronously in order to display the spinner. As soon as I call the function asynchronously however the app crashes with EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0 The only change I have made to the function is to invoke the popViewControllerAnimated lines on the main thread. Why is running this code on a new thread causing it to crash and how can I fix it?
Calling code:
-(void) _doSaveDataPoint {
[SVProgressHUD show];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self _saveDataPoint];
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
});
});
}
_saveDataPoint function. popViewController called on main thread near the end of this code:
-(void) _saveDataPoint {
NSString *errorMsg = nil;
if ([[myLegend type] isEqualToString:#"PIN"]) {
if ([myNodes count]==0) {
errorMsg = #"Please make sure you have added one point on to the map to continue.";
}
}
else if ([[myLegend type] isEqualToString:#"POLYGON"]) {
if ([myNodes count]<3) {
errorMsg = #"Please make sure you have at least 3 points set before continuing.";
}
}
else {
if ([myNodes count]<2) {
errorMsg = #"Please make sure you have at least 2 points set before continuing.";
}
}
if (errorMsg !=nil) {
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:#"Not enough points"
message:errorMsg
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
// Just dismiss
}];
[alertController addAction:okAction];
dispatch_async(dispatch_get_main_queue(), ^{
[self presentViewController:alertController animated:YES completion:nil];
});
return;
}
ClientLegendDataPointBounds *bounds = [[ClientLegendDataPointBounds alloc] init];
int count = 0;
GeoPoint *first = nil;
NSMutableDictionary *attr = [[NSMutableDictionary alloc] init];
for (_EditAnnotation *anno in myNodes) {
GeoPoint *point = [[GeoPoint alloc] initWithLatitude:[anno coordinate].latitude andLongitude:[anno coordinate].longitude];
[bounds expand:point];
if (count==0) {
first = point;
count++;
continue;
}
NSString *xKey = [NSString stringWithFormat:#"x%d",count-1];
NSNumber *xCoord = [NSNumber numberWithDouble:[point latitude ]];
NSString *yKey = [NSString stringWithFormat:#"y%d",count-1];
NSNumber *yCoord = [NSNumber numberWithDouble:[point longitude]];
[attr setObject:xCoord forKey:xKey];
[attr setObject:yCoord forKey:yKey];
count++;
}
if (count>0) {
NSString *pointCount = [NSString stringWithFormat:#"%d", count-1];
[attr setObject:pointCount forKey:#"pointCount"];
}
[self _setBarThemeDefault];
if (myDataPoint==nil) {
myDataPoint = [myLegend addDataPoint:[NSNumber numberWithLongLong:[DateTime currentTimeInMillis]] title:#"" description:#"" latitude:[first latitude] longitude:[first longitude] attributes:attr type:[myLegend type] bounds:bounds];
dispatch_async(dispatch_get_main_queue(), ^{
[[self navigationController] popViewControllerAnimated:NO];
});
[myHandler newItemCreated:myDataPoint];
} else {
[myDataPoint setAttributes:attr];
[myDataPoint setBounds:bounds];
[myDataPoint setLatitude:[first latitude]];
[myDataPoint setLongitude:[first longitude]];
[myDataPoint setModified:[NSNumber numberWithLongLong:[DateTime currentTimeInMillis]]];
[myDataPoint update];
dispatch_async(dispatch_get_main_queue(), ^{
[[self navigationController] popViewControllerAnimated:YES];
});
[myHandler itemUpdated:myDataPoint];
}
[self _finishSurveyLog:[SurveyLogItem ACT_SAVE_SPATIAL_CONST]];
[self _saveUserLocation];
}
I don't know exactly the plugin but could it be that the plugin itselfs dispatches the ui stuff to the main queue? So you don't have to dispatch the call to the main queue by yourself. Take a look at the source code:
SVProgressHUD.m

collectionView not reloading in parentviewcontroller on removal of childviewcontroller

Any one know how to reload collectionView in parentViewController when removing childViewController.
Here, I am processing on click of button adding childViewController and on click of that childViewController I am getting data and that data will transferred to parentViewController after that child view get's remove from parentViewController.
I am getting data from childViewController, also reloading collection view.
dispatch_async(dispatch_get_main_queue(),^{
[self.view layoutIfNeeded];
[self.collectionViewcellItem layoutIfNeeded];
[self.collectionViewcellItem reloadData];
});
but, no effect of reloading here seen.
means not able to change parentviewconroller view after removal of childViewController.
Thank you
Waiting for the answer and yes I am doing it in objective c.
parentViewController file.
[self.view addSubview:filterMenuVC.view];
filterMenuVC.view.backgroundColor = [UIColor clearColor];
[self addChildViewController:filterMenuVC];
[self.view addSubview:filterMenuVC.view];
[self animationSideFilterMenuBarOpen];
[filterMenuVC didMoveToParentViewController:self];
childViewController file
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%#",[NSString stringWithFormat:#"%ld",(long)indexPath.row]);
// // [wel animationSideFilterMenuBarClose];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
int categoryId = (int)cell.textLabel.tag;
[self animationSideMainMenuBarClose:categoryId];
}
-(void)animationSideMainMenuBarClose:(int)categoryId{
CGFloat width = [UIScreen mainScreen].bounds.size.width;
self.view.frame = CGRectMake(width - self.view.frame.size.width, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
[UIView animateWithDuration:0.5 animations:^{
self.view.frame = CGRectMake(width, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
}
completion:^(BOOL finished){
[self.view removeFromSuperview];
self.view = nil;
NSLog(#"category id Filter: %d",categoryId);
BOOL boolresponse = [wel getUserWork:categoryId];
if (boolresponse == NO) {
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:#""
message:#"No internet connection"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okButton = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
}];
[alert addAction:okButton];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
here, BOOL boolresponse = [wel getUserWork:categoryId]; getUserWork is the function in parentViewController, I call that and removing the childViewController. get correct data but not able to reload collectionView.
parentViewFunction which I am calling.
-(BOOL)getUserWork:(int)catergoryId{
appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
[self dismissViewControllerAnimated:true completion:^{
//do whatever you do here
[self.collectionViewcellItem reloadData];
}];
categoryIdStart = catergoryId;
Reachability *r = [[Reachability alloc]init];
if(r.currentReachabilityStatus != NotReachable) {
return NO;
}
else
{
[SVProgressHUD show];
[SVProgressHUD setStatus:#"Loading..."];
[SVProgressHUD setRingRadius:20];
[SVProgressHUD setRingThickness:10];
[SVProgressHUD setBorderColor:[UIColor orangeColor]];
[SVProgressHUD setBorderWidth:0.5];
[SVProgressHUD setForegroundColor:[UIColor orangeColor]];
NSLog(#"id category: %d",categoryIdStart);
NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys:[appDelegate.UserDic valueForKey:#"token"],#"token",[appDelegate.UserDic valueForKey:#"id"],#"id_user",[NSString stringWithFormat:#"%d",categoryIdStart],#"id_category",nil];
NSMutableArray *postArray = [NSMutableArray array];
[params enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
[postArray addObject:[NSString stringWithFormat:#"%#=%#", key, [apiCall percentEscapeString:obj]]];
}];
NSString *postString = [postArray componentsJoinedByString:#"&"];
[apiCall apiType:#"xyzzy" pD:postString dataRetrive:^(NSDictionary *dictionary){
int status = [[dictionary valueForKey:#"status"] intValue];
if (status == 0) {
[SVProgressHUD dismiss];
dispatch_async(dispatch_get_main_queue(),^{
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:#""
message:[dictionary valueForKey:#"msg"]
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okButton = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
}];
[alert addAction:okButton];
[self presentViewController:alert animated:YES completion:nil];
});
}
else{
[SVProgressHUD dismiss];
[cacheImage removeAllObjects];
dic = [dictionary valueForKey:#"data"];
NSLog(#"Category detail: %# %lu",dic,(unsigned long)dic.count);
NSLog(#"image category %# :",[dic valueForKey:#"category_name"]);
dispatch_async(dispatch_get_main_queue(),^{
[self.view layoutIfNeeded];
[self.collectionViewcellItem layoutIfNeeded];
[self.collectionViewcellItem reloadData];
[self viewWillAppear:true];
});
}
}];
return YES;
}
}

iOS Objective-C Xcode - How to start to play video in Landscape only

I'm building a App to play 360 videos - all is working great !
However, I would like like the video to start to play only if the mobile is oriented in Landscape ! IF in portrait it should display a message "Please put your mobile in landscape" and if so - start to play the video . ..
Anybody have any idea how to achieve this ?
It would be amazing :)
Thanks !
EDIT:
my Viewcontroller.m
//
// ViewController.m
// video360test
//
// Created by linyize on 16/6/20.
// Copyright © 2016年 islate. All rights reserved.
//
#import "ViewController.h"
#import "Video360ViewController.h"
#import "CardboardViewController.h"
#import "CardboardSDK.h"
#implementation ViewController
- (BOOL)prefersStatusBarHidden {
return YES;
}
- (BOOL)shouldAutorotate
{
return NO;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (IBAction)playURL:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://7b1gcw.com1.z0.glb.clouddn.com/demo1.mp4"];
Video360ViewController *videoController = [[Video360ViewController alloc] initWithNibName:#"HTY360PlayerVC" bundle:nil url:url];
if (![[self presentedViewController] isBeingDismissed]) {
[self presentViewController:videoController animated:YES completion:nil ];
}
}
- (IBAction)playFileffpvr:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"demo1" ofType:#"mp4"];
NSURL *url = [NSURL fileURLWithPath:path];
Video360ViewController *videoController = [[Video360ViewController alloc] initWithNibName:#"HTY360PlayerVC" bundle:nil url:url];
[videoController VRMode:true];
if (![[self presentedViewController] isBeingDismissed]) {
[self presentViewController:videoController animated:YES completion:nil];
}
}
- (IBAction)playFileff360:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"demo1" ofType:#"mp4"];
NSURL *url = [NSURL fileURLWithPath:path];
Video360ViewController *videoController = [[Video360ViewController alloc] initWithNibName:#"HTY360PlayerVC" bundle:nil url:url];
if (![[self presentedViewController] isBeingDismissed]) {
[self presentViewController:videoController animated:YES completion:nil];
}
}
- (IBAction)playFile2:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"boa" ofType:#"mp4"];
NSURL *url = [NSURL fileURLWithPath:path];
Video360ViewController *videoController = [[Video360ViewController alloc] initWithNibName:#"HTY360PlayerVC" bundle:nil url:url];
if (![[self presentedViewController] isBeingDismissed]) {
[self presentViewController:videoController animated:YES completion:nil];
}
}
- (IBAction)playFileffp:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"boa" ofType:#"mp4"];
NSURL *url = [NSURL fileURLWithPath:path];
Video360ViewController *videoController = [[Video360ViewController alloc] initWithNibName:#"HTY360PlayerVC" bundle:nil url:url];
if (![[self presentedViewController] isBeingDismissed]) {
[self presentViewController:videoController animated:YES completion:nil];
}
}
#end
#implementation LandscapeNavController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.navigationBarHidden=YES;
}
-(BOOL)shouldAutorotate{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskLandscape;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
EDIT 2:
the button displaying correctly the alert now:
- (IBAction)playFileffpvr:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"demo1" ofType:#"mp4"];
NSURL *url = [NSURL fileURLWithPath:path];
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIDeviceOrientationPortrait)
[self doSomething];
else
[self doSomethingElse];
Video360ViewController *videoController = [[Video360ViewController alloc] initWithNibName:#"HTY360PlayerVC" bundle:nil url:url];
[videoController VRMode:true];
if (![[self presentedViewController] isBeingDismissed]) {
[self presentViewController:videoController animated:YES completion:nil];
}
}
and the alert being display:
-(void)doSomething
{
//Show Alert
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Simple" message:#"Turn your device to Landscape." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
NSLog(#"Cancel");
}];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
NSLog(#"OK");
}];
[alertController addAction:cancelAction];
[alertController addAction:okAction];
[self presentViewController:alertController animated: YES completion: nil];
}
-(void)doSomethingElse
{
//Function Body
//play the file
}
Yes, all you need to do is create an UINavigationController subclass say LandscapeNavController and put the code below
LandscapeNavController.h
#import <UIKit/UIKit.h>
#interface LandscapeNavController : UINavigationController
#end
LandscapeNavController.m
#implementation LandscapeNavController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.navigationBarHidden=YES;
}
-(BOOL)shouldAutorotate{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskLandscape;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
Now present the video controller as modal like mentioned below
VideoController *controller=<INITIALIZE>
LandscapeNavController *nav=[[LandscapeNavController alloc] initWithRootViewController:controller];
[self presentViewController:nav animated:YES completion:nil];
and make sure your rotation settings should be
Additionally in AppDelegate.h define
#property(assign) BOOL shouldRotate;
The above property should be set to YES before you present VideoController and NO before dismissing the VideoController.
And add the following code in AppDelegate.m
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
if (shouldRotate)
return UIInterfaceOrientationMaskAll;
else
return UIInterfaceOrientationMaskPortrait;
}
Note - The above code not tested right now, if you face problem ping.
Cheers.
Declare a property for UIAlertController as:
#property (strong, nonatomic)UIAlertController *alertController;
You can Use a code like this:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(deviceOrientationDidChange) name:UIDeviceOrientationDidChangeNotification object:nil];
}
-(void)deviceOrientationDidChange
{
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIDeviceOrientationPortrait)
[self doSomething];
else
[self doSomethingElse];
}
-(void)doSomething
{
//Show Alert
self.alertController = [UIAlertController alertControllerWithTitle:#"Simple" message:#"Turn your device to Landscape." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
NSLog(#"Cancel");
}];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
NSLog(#"OK");
}];
[self.alertController addAction:cancelAction];
[self.alertController addAction:okAction];
[self presentViewController:alertController animated: YES completion: nil];
}
-(void)doSomethingElse
{
//Hide the AlertViewController
[self.alertController removeFromSuperview];
//Code to handle the playing of the file
}
-(BOOL)shouldAutorotate{
return YES;
}
Happy Coding. Hope it helps.

imagePickerControllerDidCancel with UIAlertView not working right

I am trying to present a camera view controller with a custom overlay containing two labels. I have been unable to get my imagePickerControllerDidCancel method and alertView to work properly. The system is printing the correct information to the NSLog but the lines of code that I have written are not doing anything and when the user taps 'Back' (to cancel the alertView and return to the imagePicker) the camera appears again but the takePhoto button and Cancel button are no longer accessible. They can still be seen but not tapped. When the user clicks the button at index 1 (Leave) I want the camera to be dismissed and to take the user back to my homeViewController which is at tabBarController index:1. In addition, when the camera first loads, the timerLabel is displayed with the correct data but then quickly disappears. I feel it has something to do with my refreshLabel method but again, I do not clearly understand where I am going wrong. None of these things are working for me and I'm still very new to the programming world so help with any of these matters would be greatly appreciated. thanks!
#import "CameraViewController.h"
#import "FriendsViewController.h"
#import <mobileCoreServices/UTCoreTypes.h>
#interface CameraViewController ()
#end
#implementation CameraViewController
#synthesize titleLabel;
#synthesize timerLabel;
- (void)viewDidLoad
{ [super viewDidLoad];
self.recipients = [[NSMutableArray alloc] init];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if (self.image == nil && [self.videoFilePath length] == 0) {
self.imagePickerController = [[UIImagePickerController alloc] init];
self.imagePickerController.delegate = self;
self.imagePickerController.allowsEditing = NO;
self.imagePickerController.videoMaximumDuration = 10;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;}
self.imagePickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:self.imagePickerController.sourceType];
[self presentViewController:self.imagePickerController animated:NO completion:nil];}
[[NSBundle mainBundle] loadNibNamed:#"OverlayView" owner:self options:nil];
self.overlayView.frame = CGRectMake(160,8,0,0);
self.imagePickerController.cameraOverlayView = self.overlayView;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *deadline = [NSString stringWithFormat:#"%#/deadline.txt",
documentsDirectory];
NSString *name = [NSString stringWithFormat:#"%#/name.txt",
documentsDirectory];
NSError *fileError;
titleLabel.text = [NSString stringWithContentsOfFile:name
encoding:NSASCIIStringEncoding
error:&fileError];
timerLabel.text = [NSString stringWithContentsOfFile:deadline
encoding:NSASCIIStringEncoding
error:&fileError];
if(fileError.code == 0){
NSLog(#"deadline.txt was read successfully with these contents: %#,",
timerLabel.text);
NSLog(#"name.txt was read successfully with these contents: %#,",
titleLabel.text);}
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(refreshLabel)
userInfo:nil
repeats:YES];
}
-(void)refreshLabel;{
self.formatter = [NSDateFormatter new];
[self.formatter setDateFormat:#"dd:hh:mm:ss"];
NSDate *startDate = [self.formatter dateFromString:self.timerLabel.text];
NSDate *timeLeft = [startDate dateByAddingTimeInterval:-1];
NSTimeInterval totalCountdownInterval = -1;
NSTimeInterval elapsedTime = [timeLeft timeIntervalSinceNow];
NSTimeInterval remainingTime = totalCountdownInterval - elapsedTime;
if (remainingTime <= 0.0) {
//dismiss controller and set to homecontroller at tabBar index 1
}
self.timerLabel.text = [self.formatter stringFromDate:timeLeft];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Are you Sure?"
message:#"you can't come back"
delegate:self cancelButtonTitle:#"Back" otherButtonTitles:#"Yes", nil];
[alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex==1) {
[self.imagePickerController dismissViewControllerAnimated:NO completion:nil];
[self.tabBarController setSelectedIndex:1];
NSLog(#"Leave clicked");
}
else {
[self reset];
NSLog(#"cancel clicked");
}
}
- (void)reset {
self.image = nil;
self.videoFilePath = nil;
}

ScrollView scroll to top animted YES doesn't animate

This is my first post because I usually find all the answers on stack overflow but not this time !
I have a little problem.
I am using the following methods :
-(void)scrollToTop;
{
[_scrollView setContentOffset:CGPointZero animated:YES];
}
sometimes it animates sometimes not !
This one works :
-(void)newPage:(NSString*)href
{
if(!(_pageNumber == href.integerValue))
{
__weak id weakSelf = self;
[(PageViewController*)_preLoadPages[href] setPageMinHeight:_actualPage.height];
NSMutableArray *viewControllers = [[NSMutableArray alloc] init];
viewControllers[0] = _preLoadPages[href];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:^(BOOL finished){
[weakSelf afterLinkClicked:href];
}];
_pageNumber = href.integerValue;
}
}
- (void)afterLinkClicked:(NSString*)href
{
_pageNumber = href.integerValue;
[_preLoadPages[href] setPageMinHeight:0];
_actualPage = _preLoadPages[href];
[_preLoadPages removeAllObjects];
[self updateScrollView];
[self scrollToTop];
[self parsePage];
}
Whereas this one does not :
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
CGPoint test = [gestureRecognizer locationInView:gestureRecognizer.view];
if(test.x>=742)
{
if(_preLoadPages[#"next"]!=nil)
{
__weak id weakSelf = self;
[(PageViewController*)_preLoadPages[#"next"] setPageMinHeight:_actualPage.height];
NSMutableArray *viewControllers = [[NSMutableArray alloc] init];
viewControllers[0] = _preLoadPages[#"next"];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:^(BOOL finished){
[weakSelf afterAnimationCompleted];
}];
}
}
return YES;
}
- (void)afterAnimationCompleted
{
_pageNumber++;
[_preLoadPages[#"next"] setPageMinHeight:0];
_actualPage = _preLoadPages[#"next"];
[_preLoadPages removeAllObjects];
[self updateScrollView];
[self scrollToTop];
[self parsePage];
}
There is practically no differences between these two calls !
I have tried to use performSelector: withObject: withDelay:0 but it doesn't work too !!

Resources