I am developing AVAudioPlayer according to my project requirement. In audioplayer iam using storyboard to develope coding.In my audio player using json parser to retrieve the urls from server.And finally gave the connections from first responder to Audioviewcontroller.I Can run the audioplayer. Audioplayer is successfully playing. But view will not be displayed.Blank screen will be displayed. I can drag and drop of all buttons like play button, pause button,forward button and rewind button etc. Those are buttons are drag and drop on AudioviewController. And give the connections also.These are all buttons are not displayed on Audioviewcontroller to play the corresponding song. Plz help me any body whats the problem. I am new to the ios programming.Thanks in Advance...
Audioviewcontroller.m
-(void)updateCurrentTimeForPlayer:(AVAudioPlayer *)
{
currentTime.text = [NSString stringWithFormat:#"%d:%02d", (int)p.currentTime / 60, (int)p.currentTime % 60, nil];
progressBar.value = p.currentTime;
}
-(void)updateCurrentTime
{
[self updateCurrentTimeForPlayer:self.avPlayer];
}
-(void)updateViewForPlayerState:(AVAudioPlayer *)p
{
[self updateCurrentTimeForPlayer:p];
if (updateTimer)
[updateTimer invalidate];
if (p.playing)
{
[playButton setImage:(p.playing==YES)? pauseButtonBG:playButtonBG forState:UIControlStateNormal];
updateTimer=[NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:#selector(updateCurrentTime) userInfo:p repeats:YES];
}
else
{
[playButton setImage:(p.playing==YES)? pauseButtonBG:playButtonBG forState:UIControlStateNormal];
updateTimer=nil;
}
}
-(void)updateViewForPlayerStateInBackground:(AVAudioPlayer *)p
{
[self updateCurrentTimeForPlayer:p];
if (p.playing)
{
[playButton setImage:(p.playing==YES)? pauseButtonBG:playButtonBG forState:UIControlStateNormal];
}
else
{
[playButton setImage:(p.playing==YES)? pauseButtonBG:playButtonBG forState:UIControlStateNormal];
}
}
-(void)updateViewForPlayerInfo:(AVAudioPlayer*)p
{
duration.text = [NSString stringWithFormat:#"%d:%02d", (int)p.duration / 60, (int)p.duration % 60, nil];
progressBar.maximumValue = p.duration;
volumeSlider.value = p.volume;
}
// rewind audio player
-(void)rewind
{
AVAudioPlayer *p=rewindTimer.userInfo;
p.currentTime-=SKIP_TIME;
[self updateCurrentTimeForPlayer:p];
}
// forward audio player
-(void)forward
{
AVAudioPlayer *p=forwardTimer.userInfo;
p.currentTime+=SKIP_INTERVAL;
[self updateCurrentTimeForPlayer:p];
}
json parser::
-(void)loadData
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.teluguastrology.com"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
// delegate methods in json
-(void)connection:(NSURLConnection *)connectiondidReceiveResponse:(NSURLResponse *)response
{
[_data setLength:0];
NSLog(#"didReceiveResponse called");
}
//connection did receive data
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData *)data
{
[_data appendData:data];
}
// connection did finish loading
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:_data options:kNilOptions error:&jsonError];
if ([jsonObject isKindOfClass:[NSArray class]])
{
//NSArray *jsonArray = (NSArray *)jsonObject;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSArray *array=[[NSArray alloc]init];
array=[jsonDictionary objectForKey:#"audio-urls"];
dataDictionary=[array objectAtIndex:0];
/* NSLog(#"%#",dataDictionary);*/
}
[urlsArray addObject:[dataDictionary objectForKey:#"Meshamu-Aries"]];
NSLog(#"%#",urlsArray);
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// [connection release];
NSLog(#"didFailWithError called");
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
// self.view.backgroundColor=[UIColor redColor];
urlsArray=[[NSMutableArray alloc]init];
[super viewDidLoad];
playButtonBG=[[UIImage imageNamed:#"audio_play.png"]init];
pauseButtonBG=[[UIImage imageNamed:#"audio_pause.png"]init];
[playButton setImage:playButtonBG forState:UIControlStateNormal];
//[self registerForBackGroundNotification];
updateTimer=nil;
rewindTimer=nil;
forwardTimer=nil;
// to adjust the font in label to using following method
duration.adjustsFontSizeToFitWidth=YES;
currentTime.adjustsFontSizeToFitWidth=YES;
progressBar.minimumValue=0.0;
_data=[[NSMutableData alloc]init];
[self loadData];
backgroundImg=[[UIImageView alloc]init];
backgroundImg.image=[UIImage imageNamed:#"image.png"];
[self.view addSubview:backgroundImg];
}
-(void)pausePlaybackForPlayer:(AVAudioPlayer *)p
{
[p pause];
[self updateViewForPlayerState:p];
}
-(void)startPlaybackForPlayer:(AVAudioPlayer *)p
{
if([p play])
{
[self updateViewForPlayerState:p];
}
else
NSLog(#"Could not play %#\n", p.url);
}
-(IBAction)playButtonPressed:(UIButton *)sender
{
if (avPlayer.playing==YES)
[self pausePlaybackForPlayer:avPlayer];
else
[self startPlaybackForPlayer:avPlayer];
}
-(IBAction)rewindButtonPressed:(UIButton *)sender
{
if(rewindTimer)
[rewindTimer invalidate];
rewindTimer=[NSTimer scheduledTimerWithTimeInterval:SKIP_INTERVAL target:self selector:#selector(rewind) userInfo:avPlayer repeats:YES];
}
-(IBAction)rewindButtonReleased:(UIButton *)sender
{
if(rewindTimer)
[rewindTimer invalidate];
rewindTimer=nil;
}
-(IBAction)forwardButtonPressed:(UIButton *)sender
{
if(forwardTimer)
[forwardTimer invalidate];
forwardTimer=[NSTimer scheduledTimerWithTimeInterval:SKIP_TIME target:self selector:#selector(forward) userInfo:avPlayer repeats:YES];
}
-(IBAction)forwardButtonReleased:(UIButton *)sender
{
if(forwardTimer)
[forwardTimer invalidate];
forwardTimer=nil;
}
-(IBAction)volumeSliderMoved:(UISlider *)sender
{
avPlayer.volume=[sender value];
}
-(IBAction)progressBarMoved:(UISlider *)sender
{
avPlayer.currentTime=[sender value];
[self updateCurrentTimeForPlayer:avPlayer];
}
Audioviewcontroller.h
#interface AudioViewController : UIViewController<AVAudioPlayerDelegate,NSURLConnectionDelegate>
{
IBOutlet UILabel *astroName;
IBOutlet UIButton *playButton;
IBOutlet UIButton *forwardButton;
IBOutlet UIButton *rewindButton;
IBOutlet UISlider *volumeSlider;
IBOutlet UILabel *currentTime;
IBOutlet UILabel *duration;
IBOutlet UISlider *progressBar;
UIImage *playButtonBG;
UIImage *pauseButtonBG;
NSTimer *forwardTimer;
NSTimer *rewindTimer;
NSTimer *updateTimer;
UIImageView *backgroundImg;
BOOL inBackground;
NSURLConnection *connect;
NSMutableData *responseData;
NSMutableData *downloadData;
NSMutableString *responseString;
NSMutableArray *urlsArray;
NSMutableData *_data;
NSDictionary *dataDictionary;
}
- (IBAction)playButtonPressed:(UIButton*)sender;
- (IBAction)rewindButtonPressed:(UIButton*)sender;
- (IBAction)rewindButtonReleased:(UIButton*)sender;
- (IBAction)forwardButtonPressed:(UIButton*)sender;
- (IBAction)forwardButtonReleased:(UIButton*)sender;
- (IBAction)volumeSliderMoved:(UISlider*)sender;
-(IBAction)progressBarMoved:(UISlider *)sender;
-(void)registerForBackGroundNotification;
#property(nonatomic,retain) UILabel *astroName;
#property(nonatomic,retain) UIButton *playButton;
#property(nonatomic,retain) UIButton *pauseButton;
#property(nonatomic,retain) UIButton *forwardButton;
#property(nonatomic,retain) UIButton *rewindButton;
#property(nonatomic,retain) UISlider *volumeSlider;
#property(nonatomic,retain) UISlider *progressBar;
#property(nonatomic,retain) UILabel *currentTime;
#property(nonatomic,retain) UILabel *duration;
#property(nonatomic,retain) NSTimer *updateTimer;
#property(nonatomic,retain) AVAudioPlayer *avPlayer;
#property(nonatomic,assign) BOOL *inBackGround;
#property(nonatomic,retain) UIImageView *backgroundImg;
#property(retain, nonatomic) NSMutableData* responseData;
#property(nonatomic,strong) NSData *downloadData;
#property(nonatomic,strong) NSMutableString *responseString;
#property (nonatomic,assign)int selectedIndex;
#end
Just try to comment this line of code. You have added UIImageView to self.view after adding all button. Please add this by using storyboard.
//[self.view addSubview:backgroundImg];
Good Luck !!
Related
I'm having some kind of problems with one thing, i'm making an app and i have a webview that shows a pdf file, and i have a button if clicked will call an UIDocumentInteractionController (open the pdf in a new window).
I will leave screenshots to make it easier:
When i open the app:
http://imgur.com/dpIEd
After i open the UIDocumentInteractionController:
http://imgur.com/VYV2N
Here's the code too
.h file
#interface pdfView : UIViewController <UIDocumentInteractionControllerDelegate>
{
IBOutlet UIActivityIndicatorView *loading;
IBOutlet UIWebView *Wview;
UIDocumentInteractionController *controller;
}
#property (nonatomic, retain) IBOutlet UIActivityIndicatorView *loading;
#property (nonatomic, retain) IBOutlet UIWebView *Wview;
#property (nonatomic, retain) UIDocumentInteractionController *controller;
-(void)buttonPressed;
-(IBAction)open_in:(id)sender;
-(IBAction)back:(id)sender;
#end
.m file
#import "pdfView.h"
#implementation pdfView
#synthesize loading,Wview;
#synthesize controller;
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)viewDidLoad
{
[loading startAnimating];
[super viewDidLoad];
Wview.scalesPageToFit = TRUE;
Wview.multipleTouchEnabled = TRUE;
[Wview setOpaque:NO];
NSString *path = [[NSBundle mainBundle] pathForResource:#"guia_seguranca_2" ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[Wview loadRequest:request];
[loading stopAnimating];
}
-(IBAction)open_in:(id)sender
{
NSString *fileToOpen = [[NSBundle mainBundle] pathForResource:#"guia_seguranca_2" ofType:#"pdf"];
UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:fileToOpen]];
preview.delegate = self;
[preview presentPreviewAnimated:YES];
[preview retain];
}
-(IBAction)back:(id)sender
{
[self.view removeFromSuperview];
}
-(void)buttonPressed
{
//[self.view removeFromSuperview];
NSString *fileToOpen = [[NSBundle mainBundle] pathForResource:#"guia_seguranca_2" ofType:#"pdf"];
UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:fileToOpen]];
preview.delegate = self;
[preview presentPreviewAnimated:YES];
[preview retain];
}
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
return self;
}
- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
return self.view;
}
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller
{
return self.view.frame;
}
- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller
{
[self.controller autorelease];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[super dealloc];
[Wview release];
[loading release];
}
#end
Thanks in advance.....
I would suggest not useing the webview and using a pdf app (ibook, cloudreader) like this.
//name of pdf
NSString * pathString = #"userguide";
//get pdf path
NSString * filePath = [[NSBundle mainBundle] pathForResource:pathString ofType:#"pdf"];
NSURL *url = [NSURL fileURLWithPath:filePath];
self.docController = [UIDocumentInteractionController interactionControllerWithURL:url];
BOOL isValid = [self.docController presentOpenInMenuFromRect:self.handBookLaunch.frame inView:self.view animated:YES];
if (!isValid) {
NSString * messageString = [NSString stringWithFormat:#"No PDF reader was found on your device. Please download a PDF reader (eg. iBooks)."];
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:messageString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
Solved, added this code for layout verification:
-(void) viewWillAppear:(BOOL)animated
{
CGRect arect=[[UIScreen mainScreen]applicationFrame];
CGRect anotherrect=[[UIApplication sharedApplication]statusBarFrame];
if(self.view.center.y==arect.size.height/2)
self.view.center=CGPointMake(self.view.center.x, self.view.center.y+anotherrect.size.height); // fix silliness in IB that makes view start 20 pixels higher than it should on iPhone
}
source: https://discussions.apple.com/thread/2658315?start=0&tstart=0
I have used the below code. In this code I am showing images that are coming from the webservices. To increase the scroll speed of tabelview I use UIImageView+WebCache it increase the scrolling speed fast but image is show when I touch the imageview. How to show the images when tabelview is display
NSString *str=[self.uploadimagearry objectAtIndex:indexPath.row];
// NSString *str1=[str stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSURL *uploadimageURL = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// NSData *imgdata=[NSData dataWithContentsOfURL:uploadimageURL];
//UIImage * uploadimage = [UIImage imageWithData:imgdata];
cell.imageView.frame=CGRectMake(0, -15, 50, 35);
//[cell.imageView setImageWithURL:uploadimageURL];
[cell.imageView setImageWithURL:uploadimageURL];
You have to start NSUrlConnection in a different run-loop, so that you receive data while the table is scrolling.
Just check out below examples :
LazyTableImages
Lazy loading multiple images on background threads on the iPhone
//JImage.h
#import <Foundation/Foundation.h>
#interface JImage : UIImageView {
NSURLConnection *connection;
NSMutableData* data;
UIActivityIndicatorView *ai;
}
-(void)initWithImageAtURL:(NSURL*)url;
#property (nonatomic, retain) NSURLConnection *connection;
#property (nonatomic, retain) NSMutableData* data;
#property (nonatomic, retain) UIActivityIndicatorView *ai;
#end
//JImage.m
#import "JImage.h"
#implementation JImage
#synthesize ai,connection, data;
-(void)initWithImageAtURL:(NSURL*)url {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[self setContentMode:UIViewContentModeScaleToFill];
if (!ai){
[self setAi:[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]];
[ai startAnimating];
[ai setFrame:CGRectMake(27.5, 27.5, 20, 20)];
[ai setColor:[UIColor blackColor]];
[self addSubview:ai];
}
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
if (data==nil) data = [[NSMutableData alloc] initWithCapacity:5000];
[data appendData:incrementalData];
NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[data length]];
NSLog(#"resourceData length: %d", [resourceLength intValue]);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection error...");
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[ai removeFromSuperview];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[self setImage:[UIImage imageWithData: data]];
[ai removeFromSuperview];
}
#end
//Include the definition in your class where you want to use the image
-(UIImageView*)downloadImage:(NSURL*)url:(CGRect)frame {
JImage *photoImage=[[JImage alloc] init];
photoImage.backgroundColor = [UIColor clearColor];
[photoImage setFrame:frame];
[photoImage setContentMode:UIViewContentModeScaleToFill];
[photoImage initWithImageAtURL:url];
return photoImage;
}
//How to call the class
UIImageView *imagV=[self downloadImage:url :rect];
//you can call the downloadImage function in looping statement and subview the returned imageview.
//it will help you in lazy loading of images.
//Hope this will help
Actually I am Making an Alarm app. In that When i set the Time The UILocalNotification event happens at that time and it calls the method of AppDelegate class i.e didReceiveNotifications method. In this method i have written a code to call a method of SetViewController (showReminder method) and now in this method i want that it should show a NewViewController i.e TimeViewController as i have to show animation when the Alarm Invokes.
I need this as When Alarm invokes i have setted a Action sheet to appear but i wanted to show animation also.Action sheet appears in all views But the animation can be Shown in only particular view, that's why i need to show A different ViewController.
Here is the code for what i am trying :-
I have tried al these also like PresentModalViewController, dismissModalViewController, AddSubview, remove superView... but result are negative :( what should i do..?
Almost Whole CODE:--
AppDelegate Class :-
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
if (notification){
NSLog(#"In did Notification");
NSString *reminderText = [notification.userInfo objectForKey:kRemindMeNotificationDataKey];
[viewController showReminder:reminderText];
application.applicationIconBadgeNumber = 0;
}
}
setViewController.h :-
#interface SetAlarmViewController : UIViewController <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIActionSheetDelegate>{
IBOutlet UITableView *tableview;
IBOutlet UIDatePicker *datePicker;
IBOutlet UITextField *eventText;
TPKeyboardAvoidingScrollView *scrollView;
IBOutlet UINavigationBar *titleBar;
IBOutlet UIButton *setAlarmButton;
AVAudioPlayer *player;
int index;
The420DudeAppDelegate *appDelegate;
TimeViewController *viewController;
IBOutlet UIImageView *animatedImages;
NSMutableArray *imageArray;
AVPlayerItem *player1,*player3;
AVPlayerItem *player2,*player4;
AVQueuePlayer *queuePlayer;
}
#property (nonatomic, retain) IBOutlet UIImageView *animatedImages;
#property (nonatomic, retain) IBOutlet UITableView *tableview;
#property (nonatomic, retain) IBOutlet UIDatePicker *datePicker;
#property (nonatomic, retain) IBOutlet UITextField *eventText;
#property (nonatomic, retain) TPKeyboardAvoidingScrollView *scrollView;
#property(nonatomic, retain) IBOutlet UINavigationBar *titleBar;
#property(nonatomic, retain) IBOutlet UIButton *setAlarmButton;
#property(nonatomic) UIReturnKeyType returnKeyType;
#property(nonatomic, retain) IBOutlet TimeViewController *viewController;
- (IBAction) scheduleAlarm:(id)sender;
- (void)showReminder:(NSString *)text;
-(IBAction)onTapHome;
-(IBAction)onTapChange:(id)sender;
#end
SetViewController.m :-
#synthesize datePicker,tableview, eventText,titleBar,setAlarmButton,returnKeyType,scrollView,animatedImages,viewController;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (The420DudeAppDelegate *)[[UIApplication sharedApplication] delegate];
eventText.returnKeyType = UIReturnKeyDone;
viewController = [[TimeViewController alloc] initWithNibName:#"TimeViewController" bundle:nil];
NSDate *now = [NSDate date];
[datePicker setDate:now animated:YES];
eventText.delegate = self;
index = 0;
NSString *path1 = [[NSBundle mainBundle] pathForResource:#"inhale" ofType:#"mp3"];
NSURL *url1 = [NSURL fileURLWithPath:path1];
player1 = [[AVPlayerItem alloc]initWithURL:url1];
NSString *path3 = [[NSBundle mainBundle] pathForResource:#"sound1" ofType:#"wav"];
NSURL *url3 = [NSURL fileURLWithPath:path3];
player3 = [[AVPlayerItem alloc]initWithURL:url3];
NSString *path2 = [[NSBundle mainBundle] pathForResource:#"exhale" ofType:#"mp3"];
NSURL *url2 = [NSURL fileURLWithPath:path2];
player2 = [[AVPlayerItem alloc]initWithURL:url2];
NSString *path4 = [[NSBundle mainBundle] pathForResource:#"Dude" ofType:#"mp3"];
NSURL *url4 = [NSURL fileURLWithPath:path4];
player4 = [[AVPlayerItem alloc]initWithURL:url4];
NSArray *items = [[NSArray alloc]initWithObjects:player1,player3,player2,player4,nil];
queuePlayer = [[AVQueuePlayer alloc] initWithItems:items];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(playEnded) name:AVPlayerItemDidPlayToEndTimeNotification object:player4];
}
-(void)onAlarmInvoke
{
animatedImages = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
animatedImages.userInteractionEnabled = YES;
[animatedImages setContentMode:UIViewContentModeScaleToFill];
[self.view addSubview : animatedImages];
[queuePlayer play];
// Array to hold jpg images
imageArray = [[NSMutableArray alloc] initWithCapacity:IMAGE_COUNT];
// Build array of images, cycling through image names
for (int i = 1; i <= IMAGE_COUNT; i++)
[imageArray addObject:[UIImage imageNamed:[NSString stringWithFormat:#"animation(%d).jpg", i]]];
animatedImages.animationImages = [NSArray arrayWithArray:imageArray];
// One cycle through all the images takes 1.0 seconds
animatedImages.animationDuration = 12.0;
// Repeat foreverlight electro / 4 sec.
animatedImages.animationRepeatCount = -1;
// Add subview and make window visible
// [self.view addSubview:animatedImages];
animatedImages.image = [imageArray objectAtIndex:imageArray.count - 1];
// Start it up
[animatedImages startAnimating];
// Wait 5 seconds, then stop animation
[self performSelector:#selector(stopAnimation) withObject:nil afterDelay:15000];
}
-(void)playEnded
{
[self performSelector:#selector(playNextItem) withObject:nil afterDelay:5.0];
}
-(void)playNextItem
{
[queuePlayer play];
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
[scrollView adjustOffsetToIdealIfNeeded];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:YES];
[self.tableview reloadData];
}
- (IBAction) scheduleAlarm:(id)sender {
[eventText resignFirstResponder];
// Get the current date
NSDate *pickerDate = [self.datePicker date];
// NSDate *selectedDate = [datePicker date]; // you don't need to alloc-init the variable first
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *dc = [cal components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:pickerDate];
pickerDate = [cal dateFromComponents:dc];
NSLog(#"%# is the date in picker date",pickerDate);
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = pickerDate;
// NSLog(#"%#",localNotif.fireDate);
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// NSLog(#"%#",localNotif.timeZone);
// Notification details
localNotif.alertBody = [eventText text];
// Set the action button
localNotif.alertAction = #"Show me";
localNotif.repeatInterval = NSDayCalendarUnit;
localNotif.soundName = #"jet.wav";
// Specify custom data for the notification
NSDictionary *userDict = [NSDictionary dictionaryWithObject:eventText.text
forKey:kRemindMeNotificationDataKey];
localNotif.userInfo = userDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
[self.tableview reloadData];
eventText.text = #"";
viewController = [[TimeViewController alloc] initWithNibName:#"TimeViewController" bundle:nil];
[self presentModalViewController:viewController animated:YES];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
index = indexPath.row;
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Warning!!!"
message:#"Are you sure you want to Delete???" delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok",nil];
[alertView show];
[alertView release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
UILocalNotification *notify = [notificationArray objectAtIndex:index];
if(buttonIndex == 0)
{
// Do Nothing on Tapping Cancel...
}
if(buttonIndex ==1)
{
if(notify)
[[UIApplication sharedApplication] cancelLocalNotification:notify];
}
[self.tableview reloadData];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row];
[cell.textLabel setText:notif.alertBody];
[cell.detailTextLabel setText:[notif.fireDate description]];
return cell;
}
- (void)viewDidUnload {
datePicker = nil;
tableview = nil;
eventText = nil;
[self setScrollView:nil];
[super viewDidUnload];
}
- (void)showReminder:(NSString *)text {
[self onAlarmInvoke];
[self.view addSubview:viewController.view];
UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:#"Cancel" otherButtonTitles:nil];
[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
CGRect rect = self.view.frame;
// if(rect.origin.y <= 480)
// rect.origin.y +=20;
self.view.frame = rect;
[actionSheet showInView:self.view];
[actionSheet release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0)
{
[player stop];
NSLog(#"OK Tapped");
}
if(buttonIndex == 1)
{
[player stop];
NSLog(#"Cancel Tapped");
}
}
-(IBAction)onTapHome{
viewController = [[TimeViewController alloc] initWithNibName:#"TimeViewController" bundle:nil];
[self presentModalViewController:viewController animated:YES];
}
- (void)dealloc {
[super dealloc];
[datePicker release];
[tableview release];
[eventText release];
[scrollView release];
}
-(IBAction)onTapChange:(id)sender{
SetTimeViewController *viewC = [[SetTimeViewController alloc]initWithNibName:#"SetTimeViewController" bundle:nil];
[self presentModalViewController:viewC animated:YES];
}
#end
Your viewController is probably showing the view, but without the SetViewController's view on the screen you can't see it. Your going to have to first go to the SetViewController and then present your TimeViewController. Is this right, you want to show the SetViewController but call the showReminder: method right away? But only from the didReceiveLocalNotification:.
If this is the case, set a flag,and a text property in your SetViewControllers .h,
BOOL isFromNotification;
NSString *notifText;
and present the SetViewController,and set the flag
SetViewController *setViewController = [SetViewController alloc]........
setViewController.isFromNotification = YES;
setViewController.notifText = reminderText;
[self presentModalViewController animated:YES}
and then in the viewDidAppear: of SetViewController
if(isFromNotification = YES){
[self showReminders:notifText];
}
If I got you right ,
upon notification you would like to show animation on a new view and then show the action sheet ?
Right now you call from appdelegate
[viewController showReminder:reminderText];
which by the way should be self.viewcontroller or _viewcontroller for the actually retained object
In showreminder you call
animation, which in itself adds a subview and by the way is running in the same thread , ie in serial.
and then you add the viewcontroller again as a subview.
and then you try to add the actionsheet from parent to the subview(viewcontroller), when actionsheet should probably be in the viewcontroller itself.
Did i get that right ?
No sure really whats breaking down, could be on several areas, as pointed out above.
I would :
make sure you call the retained objects through valid pointers ( using self for instance)
have a viewcontroller that you present modal as a subview that show animations on a separate thread (performselectoronthread) and have the actionsheet on that.
Then if you need to call the parent, you setup a delegate or you do the ugly way.
self.yourviewcontroller.myParentObj = self
ie set a yourviewcontroller pointer on the sub viewcontroller, which you can then openly call like
[self.myParentObj whatevermethod_you_have_in_parent];
But then again I write this from top of my head..
I have done a singleton class called MyBgMusic.h & MyBgMusic.m. How to reference that singleton class to my SecondViewController or the rest of the XIB.
Here is my singleton class:
H file :
#import <Foundation/Foundation.h>
#import <AVFoundation/AVAudioPlayer.h>
#interface MyBgMusic : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *player;
UIButton *playBgMusic;
}
#property (nonatomic, retain) IBOutlet AVAudioPlayer *player;
#property (nonatomic, retain) IBOutlet UIButton *playBgMusic;
+ (id)sharedManager;
-(IBAction) toggleMusic;
#end
M file :
#import "MyBgMusic.h"
static MyBgMusic *sharedMyManager = nil;
#implementation MyBgMusic
#synthesize player,playBgMusic;
#pragma mark -
#pragma mark Singleton Methods
+ (MyBgMusic*)sharedManager {
static MyBgMusic *sharedMyManager;
if(!sharedMyManager) {
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
sharedMyManager = [[super allocWithZone:nil] init];
});
}
return sharedMyManager;
}
+ (id)allocWithZone:(NSZone *)zone {
return [self sharedManager];
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
#if (!__has_feature(objc_arc))
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; //denotes an object that cannot be released
}
- (id)autorelease {
return self;
}
- (void)dealloc
{
[MyBgMusic release];
[playBgMusic release];
[player release];
[super dealloc];
}
#endif
#pragma mark -
#pragma mark Custom Methods
- (IBAction)toggleMusic {
if ([self.player isPlaying] == YES) {
[self.player stop];
} else {
[self.player play];
}
self.playBgMusic.enabled = YES;
}
- (void)viewDidLoad
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"music" ofType:#"mp3"];
self.player=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
player.delegate = self;
[player play];
player.numberOfLoops = -1;
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
SecondViewController.m ( I want to reference from the singleton class so that I can use it all over again without mess up the background music when pressing on and off. )
- (IBAction)toggleMusic{
if ([self.player isPlaying] == YES) {
[self.player stop];
} else {
[self.player play];
}
self.playBgMusic.enabled = YES;
}
Should I declare like this :
-(IBAction) sharedMusic {
[[MyBgMusic sharedManager] toggleMusic]; // instance method shareManager not found. What does it mean?
}
Create an IBAction in your SecondViewController hook up the xib then in code then have it call
[[MyBgMusic sharedInstance] toggleMusic];
In SecondViewController you should call [[MyBgMusic sharedInstance] toggleMusic];in the IBAction when you want to toggle music. Just as you used self.player.
You have to import your class and reference it wherever you want using this line :
[[MyBgMusic sharedManager] toggleMusic]
If you want, you can add even property and reference it without create an instance of your class.
I'm reading "beginning iPad application development", and at the bluetooth chapter i'm testing the code exactly as it appears at the book. The only difference is that the book was for 3.2 and I'm using XCODE 4 for iOS >4.0.
XCODE does not throw any error or warning, it builds correctly, but when testing at the iPhone it doesn't discover other devices.
What's wrong?
The viewController.h looks like:
#import <UIKit/UIKit.h>
#import <GameKit/GameKit.h>
#interface pruebaBluetoothViewController : UIViewController
<GKSessionDelegate, GKPeerPickerControllerDelegate> {
GKSession *currentSession;
IBOutlet UITextField *txtMessage;
IBOutlet UIButton *connect;
IBOutlet UIButton *disconnect;
GKPeerPickerController *picker;
}
#property (nonatomic, retain) GKSession *currentSession;
#property (nonatomic, retain) UITextField *txtMessage;
#property (nonatomic, retain) UIButton *connect;
#property (nonatomic, retain) UIButton *disconnect;
-(IBAction) btnSend:(id) sender;
-(IBAction) btnConnect:(id) sender;
-(IBAction) btnDisconnect:(id) sender;
#end
While the .m looks like:
#import "pruebaBluetoothViewController.h"
#implementation pruebaBluetoothViewController
#synthesize currentSession;
#synthesize txtMessage;
#synthesize connect;
#synthesize disconnect;
- (void)viewDidLoad {
[connect setHidden:NO];
[disconnect setHidden:YES];
[super viewDidLoad];
}
-(IBAction) btnConnect:(id) sender {
picker = [[GKPeerPickerController alloc] init];
picker.delegate = self;
picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
[connect setHidden:YES];
[disconnect setHidden:NO];
[picker show];
}
- (void)peerPickerController:(GKPeerPickerController *)pk
didConnectPeer:(NSString *)peerID
toSession:(GKSession *) session {
self.currentSession = session;
session.delegate = self;
[session setDataReceiveHandler:self withContext:nil];
picker.delegate = nil;
[picker dismiss];
[picker autorelease];
}
- (void)peerPickerControllerDidCancel:(GKPeerPickerController *)pk {
picker.delegate = nil;
[picker autorelease];
[connect setHidden:NO];
[disconnect setHidden:YES];
}
-(IBAction) btnDisconnect:(id) sender {
[self.currentSession disconnectFromAllPeers];
[self.currentSession release];
currentSession = nil;
[connect setHidden:NO];
[disconnect setHidden:YES];
}
- (void)session:(GKSession *)session
peer:(NSString *)peerID
didChangeState:(GKPeerConnectionState)state {
switch (state) {
case GKPeerStateConnected:
NSLog(#"connected");
break;
case GKPeerStateDisconnected:
NSLog(#"disconnected");
[self.currentSession release];
currentSession = nil;
[connect setHidden:NO];
[disconnect setHidden:YES];
break;
}
}
- (void)dealloc {
[txtMessage release];
[currentSession release];
[super dealloc];
}
- (void) mySendDataToPeers:(NSData *) data {
if (currentSession)
[self.currentSession sendDataToAllPeers:data
withDataMode:GKSendDataReliable
error:nil];
}
-(IBAction) btnSend:(id) sender {
//---convert an NSString object to NSData---
NSData* data;
NSString *str = [NSString stringWithString:txtMessage.text];
data = [str dataUsingEncoding: NSASCIIStringEncoding];
[self mySendDataToPeers:data];
}
- (void) receiveData:(NSData *)data
fromPeer:(NSString *)peer
inSession:(GKSession *)session
context:(void *)context {
//---convert the NSData to NSString---
NSString* str;
str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Data received"
message:str
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
looks like you missed the following Delegate Method:
- (GKSession *)peerPickerController:(GKPeerPickerController *)picker sessionForConnectionType:(GKPeerPickerConnectionType)type {
GKSession *session = [[GKSession alloc] initWithSessionID:kTankSessionID displayName:nil sessionMode:GKSessionModePeer];
return [session autorelease]; // peer picker retains a reference, so autorelease ours so we don't leak.
}
Hope this helps.