Tab bar Controller and Facebook Connect Issues Xcode 4.3 IOS 5.1 - objective-c

I am trying to connect to the facebook and take the users name and picture, so far i can connect and fetch user name . i have a working code can be downloaded from here (single view application)
But if i put a tab bar controller to the code, it can not receive a response from facebook.
I add a tabbar controller programatically like below code
in app.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Regular Code
/*self.viewController = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
*/
//Tab bar controller code
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
UIViewController *viewController1 = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
self.rootController = [[[UITabBarController alloc] init] autorelease];
self.rootController.viewControllers = [NSArray arrayWithObjects:viewController1, nil];
self.window.rootViewController = self.rootController;
[self.window makeKeyAndVisible];
return YES;
}
// This method will be used for iOS versions greater than 4.2.
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [[_viewController facebook] handleOpenURL:url];
}
If i put a breaking point at line handleOpenurl In NSUrl there is this= fbAPPID://authorize/#access_token=BABABSbbsabsbabb
I guess access_token means i have succesfully loged in . So tab bar doesnt block me to login put blokcs my facebook methods in Viewcontroller.m
Without tab bar all methods in Viewcontroller.m works great when i add tab bar and breakpoints none of the facebook methods below works. I dont get any errors though.
-(void)request:(FBRequest *)request didLoad:(id)result
-(void)fbDidLogin
ViewController.m
#import "ViewController.h"
#import "FBConnect.h"
#import "Facebook.h"
#implementation ViewController
#synthesize btnLogin;
#synthesize btnPublish;
#synthesize lblUser;
#synthesize actView;
#synthesize facebook;
#synthesize permissions;
#synthesize isConnected;
#synthesize imageView;
// The alert view that will be shown while the game will upload to facebook.
UIAlertView *msgAlert;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
-(void)checkForPreviouslySavedAccessTokenInfo{
// Initially set the isConnected value to NO.
isConnected = NO;
// Check if there is a previous access token key in the user defaults file.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"] &&
[defaults objectForKey:#"FBExpirationDateKey"]) {
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
// Check if the facebook session is valid.
// If it’s not valid clear any authorization and mark the status as not connected.
if (![facebook isSessionValid]) {
[facebook authorize:nil];
isConnected = NO;
}
else {
isConnected = YES;
}
}
}
-(void)setLoginButtonImage{
UIImage *imgNormal;
UIImage *imgHighlighted;
UIImageView *tempImage;
// Check if the user is connected or not.
if (!isConnected) {
// In case the user is not connected (logged in) show the appropriate
// images for both normal and highlighted states.
imgNormal = [UIImage imageNamed:#"LoginNormal.png"];
imgHighlighted = [UIImage imageNamed:#"LoginPressed.png"];
}
else {
imgNormal = [UIImage imageNamed:#"LogoutNormal.png"];
imgHighlighted = [UIImage imageNamed:#"LogoutPressed.png"];
}
// Get the screen width to use it to center the login/logout button.
// We’ll use a temporary image view to get the appopriate width and height.
float screenWidth = [UIScreen mainScreen].bounds.size.width;
tempImage = [[UIImageView alloc] initWithImage:imgNormal];
[btnLogin setFrame:CGRectMake(screenWidth / 2 - tempImage.frame.size.width / 2, btnLogin.frame.origin.y, tempImage.frame.size.width, tempImage.frame.size.height)];
// Set the button’s images.
[btnLogin setBackgroundImage:imgNormal forState:UIControlStateNormal];
[btnLogin setBackgroundImage:imgHighlighted forState:UIControlStateHighlighted];
// Release the temporary image view.
[tempImage release];
}
-(void)showActivityView{
// Show an alert with a message without the buttons.
msgAlert = [[UIAlertView alloc] initWithTitle:#"My test app" message:#"Please wait..." delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[msgAlert show];
// Show the activity view indicator.
actView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0, 0.0, 40.0, 40.0)];
[actView setCenter:CGPointMake(160.0, 350.0)];
[actView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:actView];
[actView startAnimating];
}
-(void)stopShowingActivity{
[actView stopAnimating];
[msgAlert dismissWithClickedButtonIndex:0 animated:YES];
}
-(void)saveAccessTokenKeyInfo{
// Save the access token key info into the user defaults.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[facebook accessToken] forKey:#"FBAccessTokenKey"];
[defaults setObject:[facebook expirationDate] forKey:#"FBExpirationDateKey"];
[defaults synchronize];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Set the permissions.
// Without specifying permissions the access to Facebook is imposibble.
permissions = [[NSArray arrayWithObjects:#"read_stream", #"publish_stream", nil] retain];
// Set the Facebook object we declared. We’ll use the declared object from the application
// delegate.
facebook = [[Facebook alloc] initWithAppId:#"331327710279153" andDelegate:self];
// Check if there is a stored access token.
[self checkForPreviouslySavedAccessTokenInfo];
// Depending on the access token existence set the appropriate image to the login button.
[self setLoginButtonImage];
// Specify the lblUser label's message depending on the isConnected value.
// If the access token not found and the user is not connected then prompt him/her to login.
if (!isConnected) {
[lblUser setText:#"Tap on the Login to connect to Facebook"];
}
else {
// Get the user's name from the Facebook account.
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
// Initially hide the publish button.
[btnPublish setHidden:YES];
}
- (void)viewDidUnload
{
[self setBtnLogin:nil];
[self setLblUser:nil];
[self setBtnPublish:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
// Keep this just for testing purposes.
NSLog(#"received response");
}
-(void)request:(FBRequest *)request didLoad:(id)result{
// With this method we’ll get any Facebook response in the form of an array.
// In this example the method will be used twice. Once to get the user’s name to
// when showing the welcome message and next to get the ID of the published post.
// Inside the result array there the data is stored as a NSDictionary.
if ([result isKindOfClass:[NSArray class]]) {
// The first object in the result is the data dictionary.
result = [result objectAtIndex:0];
}
// Check it the “first_name” is contained into the returned data.
if ([result objectForKey:#"first_name"]) {
// If the current result contains the "first_name" key then it's the user's data that have been returned.
// Change the lblUser label's text.
[lblUser setText:[NSString stringWithFormat:#"Welcome %#!", [result objectForKey:#"first_name"]]];
// Show the publish button.
[btnPublish setHidden:NO];
}
else if ([result objectForKey:#"id"]) {
// Stop showing the activity view.
[self stopShowingActivity];
// If the result contains the "id" key then the data have been posted and the id of the published post have been returned.
UIAlertView *al = [[UIAlertView alloc] initWithTitle:#"My test app" message:#"Your message has been posted on your wall!" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[al show];
[al release];
}
}
-(void)request:(FBRequest *)request didFailWithError:(NSError *)error{
NSLog(#"%#", [error localizedDescription]);
// Stop the activity just in case there is a failure and the activity view is animating.
if ([actView isAnimating]) {
[self stopShowingActivity];
}
}
-(void)fbDidLogin{
// Save the access token key info.
[self saveAccessTokenKeyInfo];
// Get the user's info.
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
-(void)fbDidNotLogin:(BOOL)cancelled{
// Keep this for testing purposes.
//NSLog(#"Did not login");
UIAlertView *al = [[UIAlertView alloc] initWithTitle:#"My test app" message:#"Login cancelled." delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[al show];
}
-(void)fbDidLogout{
// Keep this for testing purposes.
//NSLog(#"Logged out");
// Hide the publish button.
[btnPublish setHidden:YES];
}
- (IBAction)LoginOrLogout {
// If the user is not connected (logged in) then connect.
// Otherwise logout.
if (!isConnected) {
[facebook authorize:permissions];
// Change the lblUser label's message.
[lblUser setText:#"Please wait..."];
}
else {
[facebook logout:self];
[lblUser setText:#"Tap on the Login to connect to Facebook"];
}
isConnected = !isConnected;
[self setLoginButtonImage];
}
- (IBAction)Publish {
// Show the activity indicator.
[self showActivityView];
// Create the parameters dictionary that will keep the data that will be posted.
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"My test app", #"name",
#"http://www.google.com", #"link",
#"FBTestApp app for iPhone!", #"caption",
#"This is a description of my app", #"description",
#"Hello!\n\nThis is a test message\nfrom my test iPhone app!", #"message",
nil];
// Publish.
// This is the most important method that you call. It does the actual job, the message posting.
[facebook requestWithGraphPath:#"me/feed" andParams:params andHttpMethod:#"POST" andDelegate:self];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)dealloc {
[btnLogin release];
[lblUser release];
[btnPublish release];
[actView release];
[facebook release];
[permissions release];
[super dealloc];
}
#end
I am confused how can i make this tab bar controlling working.

I have changed the design
Now Login view is displayed first then it continues to real app which has tab bar controller.
Issue was _viewcontroller facebook , when _viewcontroller has been called it was not returning any thing
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [[_viewController facebook] handleOpenURL:url];
}
So I changed my code(especially _viewcontroller line) to below code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
UIViewController * viewController1 = [[[VoteMe alloc] initWithNibName:#"VoteMe" bundle:nil] autorelease];
UIViewController *viewController2 = [[[PostController alloc] initWithNibName:#"PostController" bundle:nil] autorelease];
UIViewController *viewController3 = [[[FriendsController alloc] initWithNibName:#"FriendsController" bundle:nil] autorelease];
UIViewController *viewController4 = [[[Responses alloc] initWithNibName:#"Responses" bundle:nil] autorelease];
UIViewController *viewController5 = [[[User alloc] initWithNibName:#"User" bundle:nil] autorelease];
self.rootController = [[[UITabBarController alloc] init] autorelease];
self.rootController.viewControllers = [NSArray arrayWithObjects:viewController1,viewController2,viewController3,viewController4,viewController5, nil];
self.window.rootViewController = self.rootController;
[self.window makeKeyAndVisible];
loginView=[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
[self.window addSubview:loginView.view];
return YES;
}
// This method will be used for iOS versions greater than 4.2.
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [[loginView facebook] handleOpenURL:url];
}
It works fine

Related

Facebook SDK 3.1 for iOS login issues

I have used Facebook sdk 3.1 in my ios app for sharing link on friends wall. I try to open a new session in the applicationDidFinishLaunching method as below
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
myAppDelegate = self;
AudioViewController *viewController = [[AudioViewController alloc] init];
self.navController = [[UINavigationController alloc] initWithRootViewController:viewController];
[self.navController setNavigationBarHidden:YES];
viewController = nil;
self.window.rootViewController = self.navController;
[self.window makeKeyAndVisible];
if (![self openSessionWithAllowLoginUI:NO]) {
// No? Display the login page.
[self performSelector:#selector(login) withObject:nil afterDelay:0.5];
}
return YES;
}
- (void)login{
[self openSessionWithAllowLoginUI:YES];
}
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
return [FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState)state
error:(NSError *)error{
switch (state) {
case FBSessionStateOpen: {
DLOG(#"session open");
}
break;
case FBSessionStateClosed: {
DLOG(#"session closed");
[FBSession.activeSession closeAndClearTokenInformation];
}
break;
case FBSessionStateClosedLoginFailed: {
DLOG(#"session Failed");
}
break;
default:
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName:WVSessionStateChangedNotification
object:session];
if (error) {
DLOG(#"error = %#",error);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:#"Error: %#",
[AppDelegate FBErrorCodeDescription:error.code]]
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
With some of the Facebook accounts it returns error "The operation could not be completed" com.facebook.sdk error 2. and so further cannot post on Facebook.
Am I doing something wrong here ?Any help would be appreciated.!
I had same issue, and i have solved it by calling openSessionWithAllowLoginUI:TRUE via NSTimer.
if (![self openSessionWithAllowLoginUI:NO]) {
// No? Display the login page.
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(login) userInfo:nil repeats:NO];
}
The reason is, we can't get FB session on different threads, either we use main thread or another(background) thread. In your code, when you check session availability, you use main thread and for login, you use different thread via performSelector function.
Hope, it will help you.
thanks

Correctly Stoping AVAudioPlayer. Currently runs in Background

I've been strugling with this problem for quite a while.
I'm trying to make a player that contains a playlist and plays only the music files stored inside the application.
Now, i'm using AVAudioPlayer to play the mp3 files. My problem is that when i load the playlist i can't stop the previous mp3 from playing and therefor i get a mixture of sounds between the first audio and all the other audio files that i load from the playlist.
so, here is my code:
#import "MainViewController.h"
#import <Foundation/Foundation.h>
#pragma mark Audio session callbacks_______________________
#implementation MainViewController
#synthesize artworkItem;
#synthesize userMediaItemCollection;
#synthesize playBarButton;
#synthesize pauseBarButton;
#synthesize musicPlayer;
#synthesize navigationBar;
#synthesize noArtworkImage;
#synthesize backgroundColorTimer;
#synthesize nowPlayingLabel, AudFile;
#synthesize appSoundButton;
#synthesize addOrShowMusicButton;
#synthesize appSoundPlayer;
#synthesize soundFileURL;
#synthesize interruptedOnPlayback;
#synthesize playedMusicOnce;
#synthesize playing;
#pragma mark Music control________________________________
- (IBAction) playOrPauseMusic: (id)sender {
}
- (IBAction) AddMusicOrShowMusic: (id) sender {
[audioPlayer stop];
// Load the Playlist direcly
MusicTableViewController *controller = [[MusicTableViewController alloc] initWithNibName: #"MusicTableView" bundle: nil];
controller.delegate = self;
controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController: controller animated: YES];
[controller release];
}
#pragma mark Application playback control_________________
- (IBAction) playAppSound: (id) sender {
// [appSoundPlayer play];
// playing = YES;
// [appSoundButton setEnabled: NO];
}
// delegate method for the audio route change alert view; follows the protocol specified
// in the UIAlertViewDelegate protocol.
- (void) alertView: routeChangeAlertView clickedButtonAtIndex: buttonIndex {
if ((NSInteger) buttonIndex == 1) {
[appSoundPlayer play];
} else {
[appSoundPlayer setCurrentTime: 0];
[appSoundButton setEnabled: YES];
}
[routeChangeAlertView release];
}
#pragma mark AV Foundation delegate methods____________
- (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) appSoundPlayer successfully: (BOOL) flag {
}
- (void) audioPlayerBeginInterruption: player {
}
- (void) audioPlayerEndInterruption: player {
}
#pragma mark Table view delegate methods________________
// Invoked when the user taps the Done button in the table view.
- (void) musicTableViewControllerDidFinish: (MusicTableViewController *) controller {
[self dismissModalViewControllerAnimated: YES];
}
#pragma mark Application setup____________________________
#if TARGET_IPHONE_SIMULATOR
#warning *** Simulator mode: iPod library access works only when running on a device.
#endif
//play audio 2
- (void)playAudio2:(NSString*) name type:(NSString*)type
{
[self stopAudio];
[audioPlayer stop];
[audioPlayer release];
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:name
ofType:type]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
}
[audioPlayer play];
}
-(void)playAudio
{
[appSoundPlayer play];
}
- (void)stopAudio
{
[appSoundPlayer stop];
}
// Configure the application.
- (void) viewDidLoad {
[super viewDidLoad];
[self setPlayedMusicOnce: NO];
[self setNoArtworkImage: [UIImage imageNamed: #"no_artwork.png"]];
[self setPlayBarButton: [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemPlay
target: self
action: #selector (playOrPauseMusic:)]];
[self setPauseBarButton: [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemPause
target: self
action: #selector (playOrPauseMusic:)]];
[addOrShowMusicButton setTitle: NSLocalizedString (#"Add Music", #"Title for 'Add Music' button, before user has chosen some music")
forState: UIControlStateNormal];
[appSoundButton setTitle: NSLocalizedString (#"Play App Sound", #"Title for 'Play App Sound' button")
forState: UIControlStateNormal];
[nowPlayingLabel setText: NSLocalizedString (#"Instructions", #"Brief instructions to user, shown at launch")];
// Configure a timer to change the background color. The changing color represents an
// application that is doing something else while iPod music is playing.
[self setBackgroundColorTimer: [NSTimer scheduledTimerWithTimeInterval: 3.5
target: self
selector: #selector (updateBackgroundColor)
userInfo: nil
repeats: YES]];
[self setupAudioSession];
}
// Invoked by the backgroundColorTimer.
- (void) updateBackgroundColor {
[UIView beginAnimations: nil context: nil];
[UIView setAnimationDuration: 3.0];
CGFloat redLevel = rand() / (float) RAND_MAX;
CGFloat greenLevel = rand() / (float) RAND_MAX;
CGFloat blueLevel = rand() / (float) RAND_MAX;
self.view.backgroundColor = [UIColor colorWithRed: redLevel
green: greenLevel
blue: blueLevel
alpha: 1.0];
[UIView commitAnimations];
}
#pragma mark Application state management_____________
- (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 {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(void) setupAudioSession
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
[audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
if (setCategoryError){/* Handle Error COndition*/}
NSError *activationError = nil;
[audioSession setActive:YES error:&activationError];
if (activationError){
/*handle error*/
}
}
// just for test , delete after
-(void) myInstanceMethod: (id)sender{
[self setupAudioSession];
[audioPlayer stop];
[audioPlayer release];
AudFile = sender;
NSLog(#"My Instance metthod called ok with item : %#", sender);
[self playAudio2:[NSString stringWithFormat:#"%#",AudFile] type:#"mp3"];
//[self setupApplicationAudio: sender];
NSLog(#"New Audfile is: %#", AudFile);
// [self setupApplicationAudio];
}
+(void) myClassMethod{
NSLog(#"Class Called ok");
}
- (void)dealloc {
/*
// This sample doesn't use libray change notifications; this code is here to show how
// it's done if you need it.
[[NSNotificationCenter defaultCenter] removeObserver: self
name: MPMediaLibraryDidChangeNotification
object: musicPlayer];
[[MPMediaLibrary defaultMediaLibrary] endGeneratingLibraryChangeNotifications];
*/
[[NSNotificationCenter defaultCenter] removeObserver: self
name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object: musicPlayer];
[[NSNotificationCenter defaultCenter] removeObserver: self
name: MPMusicPlayerControllerPlaybackStateDidChangeNotification
object: musicPlayer];
[musicPlayer endGeneratingPlaybackNotifications];
[musicPlayer release];
[artworkItem release];
[backgroundColorTimer invalidate];
[backgroundColorTimer release];
[navigationBar release];
[noArtworkImage release];
[nowPlayingLabel release];
[pauseBarButton release];
[playBarButton release];
[soundFileURL release];
[userMediaItemCollection release];
[super dealloc];
}
I am sending the file name from my playlist to my player through
-(void) myInstanceMethod: (id)sender{
[self setupAudioSession];
[audioPlayer stop];
[audioPlayer release];
AudFile = sender;
NSLog(#"My Instance metthod called ok with item : %#", sender);
[self playAudio2:[NSString stringWithFormat:#"%#",AudFile] type:#"mp3"];
//[self setupApplicationAudio: sender];
NSLog(#"New Audfile is: %#", AudFile);
// [self setupApplicationAudio];
}
and i load my playlist from my mainviewcontroller using the UIModalTransition in the method
- (IBAction) AddMusicOrShowMusic: (id) sender {
[audioPlayer stop];
// Load the Playlist direcly
MusicTableViewController *controller = [[MusicTableViewController alloc] initWithNibName: #"MusicTableView" bundle: nil];
controller.delegate = self;
controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController: controller animated: YES];
[controller release];
}
As you can see when i load my playlist i tell the player to stop playing through
[audioPlayer stop];
but for some reason it failes to stop playing, therefore creating an overlap of sounds.
This is my problem which i'm trying to figure out.
Thank you
and best regards!

reading a value from preferences

I have just recently implemented the inAppSettings kit. My goal was to load my default view and then add a navigation bar button item to the right called "settings". Once the user pressed the settings button it would take them to my settings bundle where they would make a choice to which website they wanted, and then press back which would load up my default view once again with webview loaded once again with the new url.
I have implemented everything that I just described above but once the selection is made within the settings and the user presses back (aka dismisses the settings view to go back to the default view), the app crashes and I have no idea why. My code is below and if anyone knows why this is happening, it would be much appreciated. Let it be noted that once I run the app again after it crashes, the website loads correctly based on the settings they chose before it crashed.
P.S. the options the user can click to select are: Google, stackoverflow.
ERROR Message: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Upcoming settingsViewControllerDidEnd:]: unrecognized selector sent to instance 0x281c70'
Thank you in advance
- (IASKAppSettingsViewController*)appSettingsViewController {
if (!appSettingsViewController) {
appSettingsViewController = [[IASKAppSettingsViewController alloc] initWithNibName:#"IASKAppSettingsView" bundle:nil];
appSettingsViewController.delegate = self;
}
return appSettingsViewController;
}
-(IBAction)selectSettings {
UINavigationController *aNavController = [[UINavigationController alloc] initWithRootViewController:self.appSettingsViewController];
//[viewController setShowCreditsFooter:NO]; // Uncomment to not display InAppSettingsKit credits for creators.
// But we encourage you not to uncomment. Thank you!
self.appSettingsViewController.showDoneButton = YES;
[self presentModalViewController:aNavController animated:YES];
[aNavController release];
}
-(NSDictionary *)intialDefaults {
NSArray *keys = [[[NSArray alloc] initWithObjects:kPicture, nil] autorelease];
NSArray *values= [[[NSArray alloc] initWithObjects: #"none", nil] autorelease];
return [[[NSDictionary alloc] initWithObjects: values forKeys: keys] autorelease];
}
-(void)setValuesFromPreferences {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults registerDefaults:[self intialDefaults]];
NSString *picturePreference= [userDefaults stringForKey:kPicture];
if([picturePreference isEqualToString:#"google"]) {
[self getUpcoming:#"http://www.google.ca"];
} else
if ([picturePreference isEqualToString:#"stackoverflow"]) {
[self getUpcoming:#"http://www.stackoverflow.com"];
} else {
[self getUpcoming:#"http://www.yahoo.com"];
}
}
-(void)getUpcoming:(id) hello {
NSURL *url= [NSURL URLWithString:hello];
NSURLRequest *requestURL= [NSURLRequest requestWithURL:url];
[web loadRequest:requestURL];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
web.hidden=NO;
[spinner stopAnimating];
[load_message dismissWithClickedButtonIndex:0 animated:TRUE];
pic1.hidden=YES;
}
-(void) loadMethod {
load_message = [[UIAlertView alloc] initWithTitle:#"Loading..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
spinner= [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
spinner.center = CGPointMake(135.0, 60.0);
[load_message addSubview:spinner];
[load_message show];
[spinner startAnimating];
[self performSelector:#selector(setValuesFromPreferences) withObject:nil afterDelay:0.0];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
UIBarButtonItem *settingButton= [[UIBarButtonItem alloc]
initWithTitle:#"Settings"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(selectSettings)];
self.navigationItem.rightBarButtonItem = settingButton;
web.hidden=YES;
pic1.hidden=NO;
}
- (void) viewDidAppear:(BOOL)animated {
[self loadMethod];
}
Do you implement the InAppSettingKit delegate? Add this to your current class above
- (void)settingsViewControllerDidEnd:(IASKAppSettingsViewController *)sender
{
// dismiss the view here
[self dismissModalViewControllerAnimated:YES];
// do whatever you need to do
}

UIAlertView showing up only after it's dismissed

I've been trying to figure this out for 2 days now, and before anyone posts another stackoverflow question, I've read them all and none of them cover my problem exactly:
I have a CoreData app that updates dynamically. Now during the update I want an UIAlertView to pop up saying that an update is being downloaded.
So here's the important code:
AppDelegate:
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[myUpdater checkForUpdatesInContext:self.managedObjectContext];
}
_
Updater Class:
- (void)checkForUpdatesInContext:(NSManagedObjectContext *)myManagedObjectContext
{
[self loadUpdateTime];
NSLog(#"Update start");
NSDate *now = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone localTimeZone] secondsFromGMT]];
if ([now timeIntervalSinceDate:updateTime] < UPDATE_TIME_INTERVAL)
{
return;
}
[self showAlertViewWithTitle:#"Update"];
... //updating process
[self.alertView dismissWithClickedButtonIndex:0 animated:YES];
NSLog (#"Update done");
}
- (void) showAlertViewWithTitle:(NSString *)title
{
self.alertView = [[UIAlertView alloc] initWithTitle:title message:#"Daten werden aktualisiert..." delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
... //design the alertView
[self.alertView show];
NSLog (#"AlertView shows");
}
So here is what happens when I run this:
Launch image shows
NSLog "Update starts" fires
NSLog "AlertView shows" fires
Screen dims but no AlertView is shown
Update is running
NSLog "Update done" fires
Launch image goes away and TabBarController shows up
UIAlertView shows up and is dismissed right away and the dimmed screen returns to normal
What I would like to have happen:
Launch image
TabBarController shows up
Screen dims and UIAlertView shows
Update is running
UIAlertView gets dismissed and dimmed screen returns to normal
I know it's something with the UI Thread and the main Thread and stuff.. But I tried every combination it seems but still not the expected result. Please help :)
EDIT:
HighlightsViewController Class:
- (void)viewDidLoad
{
[super viewDidLoad];
self.updater = [[Updater alloc] init];
[updater checkForUpdatesInContext:self.managedObjectContext];
... // other setup stuff nothing worth mentioning
}
Is this the right place to call [super viewDidLoad]? Because it still doesn't work like this, still the update is being done while the Launch Image is showing on the screen. :-(( I'm about to give this one up..
Here you go, in this prototype things work exactly how you want them to.
Header:
#import <UIKit/UIKit.h>
#interface AlertViewProtoViewController : UIViewController
{
}
- (void) showAlertViewWithTitle:(NSString *)title;
- (void) checkForUpdatesInContext;
- (void) update;
- (void)someMethod;
- (void)someOtherMethod;
#end
#import "AlertViewProtoViewController.h"
Class:
#implementation AlertViewProtoViewController
UIAlertView *alertView;
bool updateDone;
UILabel *test;
bool timershizzle;
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor yellowColor];
UILabel *test = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 500, 500)];
test.backgroundColor = [UIColor blueColor];
[self.view addSubview:test];
[self performSelector:#selector(checkForUpdatesInContext) withObject:nil afterDelay:0.0];
}
- (void)update
{
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; //commented for auto ref counting
NSLog(#"update start");
//your update stuff
NSLog(#"update end");
updateDone = YES;
//[pool release];
}
- (void)checkForUpdatesInContext//:(NSManagedObjectContext *)myManagedObjectContext
{
//[self loadUpdateTime];
NSLog(#"Update start");
NSDate *now = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone localTimeZone] secondsFromGMT]];
// if ([now timeIntervalSinceDate:updateTime] < UPDATE_TIME_INTERVAL)
// {
// return;
// }
[self showAlertViewWithTitle:#"Update"];
//[self setManagedObjectContext:myManagedObjectContext];
[self performSelector:#selector(someMethod) withObject:nil afterDelay:0.0];
[self performSelector:#selector(someOtherMethod) withObject:nil afterDelay:0.0];
}
-(void)someOtherMethod
{
while (!updateDone) {
// NSLog(#"waiting...");
}
[alertView dismissWithClickedButtonIndex:0 animated:YES];
NSLog (#"Update done");
self.view.backgroundColor = [UIColor greenColor];
}
-(void)someMethod
{
[self performSelectorInBackground:#selector(update) withObject:nil];
}
- (void) showAlertViewWithTitle:(NSString *)title
{
alertView = [[UIAlertView alloc] initWithTitle:title message:#"Daten werden aktualisiert..." delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
alertView.frame = CGRectMake(100, 100, 200, 200);
alertView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:alertView];
[self.view setNeedsDisplay];
NSLog (#"AlertView shows");
}
#end
You should adjust were needed for your own purposes but it works.
You are starting a background thread and then dismissing the alert immediately. I would suggest that you might use an NSNotification, posted from the background task, and received in whichever controller starts the alert, triggering a method that dismissed the alert.
I find the UIAlertView interface unsuitable for this type of user notice, and prefer to use a semi-transparent overlay view with a UIActivityIndicatorView, plus an informing message for the user.
You are doing a:
- (void)applicationDidBecomeActive:(UIApplication *)application
Isn't it so that the alertview you want to show needs a view to be loaded which isn't active yet at this point? See: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIAlertView_Class/UIAlertView/UIAlertView.html
Similar question? UIAlertView starts to show, screen dims, but it doesn't pop up until it's too late!

Objective C: Send email without leaving app

How do I send an email within an app without leaving the app.
This works:
-(void) sendEmailTo:(NSString *)to withSubject:(NSString *)subject withBody:(NSString *)body {
NSString *mailString = [NSString stringWithFormat:#"mailto:?to=%#&subject=%#&body=%#",
[to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[body stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailString]];
}
but goes to the mail app to send. Is there a way to do this without leaving the app?
Yes. Use the MFMailComposeViewController.
// From within your active view controller
if([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailCont = [[MFMailComposeViewController alloc] init];
mailCont.mailComposeDelegate = self;
[mailCont setSubject:#"yo!"];
[mailCont setToRecipients:[NSArray arrayWithObject:#"joel#stackoverflow.com"]];
[mailCont setMessageBody:#"Don't ever want to give you up" isHTML:NO];
[self presentViewController:mailCont animated:YES completion:nil];
}
// Then implement the delegate method
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[self dismissViewControllerAnimated:YES completion:nil];
}
Add MessageUI framework:
Click on the project
Select "Build Phases"
Expand "Link Binary With Libraries"
Click "+" and type "Message" to find "MessageUI" framework, then add.
In current view controller add import and implement a protocol:
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>
#interface MyViewController : UIViewController<MFMailComposeViewControllerDelegate>
Add methods:
-(void)sendEmail {
// From within your active view controller
if([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailCont = [[MFMailComposeViewController alloc] init];
mailCont.mailComposeDelegate = self; // Required to invoke mailComposeController when send
[mailCont setSubject:#"Email subject"];
[mailCont setToRecipients:[NSArray arrayWithObject:#"myFriends#email.com"]];
[mailCont setMessageBody:#"Email message" isHTML:NO];
[self presentViewController:mailCont animated:YES completion:nil];
}
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[controller dismissViewControllerAnimated:YES completion:nil];
}
Updated for iOS 6. Please note that this uses ARC and does not use the deprecated modal view presentation:
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>
#interface MyViewController : UIViewController<MFMailComposeViewControllerDelegate>
And then the code to present the email screen:
- (IBAction)emailButtonPushed:(id)sender {
if([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailCont = [[MFMailComposeViewController alloc] init];
mailCont.mailComposeDelegate = self;
[mailCont setSubject:#"Your email"];
[mailCont setMessageBody:[#"Your body for this message is " stringByAppendingString:#" this is awesome"] isHTML:NO];
[self presentViewController:mailCont animated:YES completion:nil];
}
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
//handle any error
[controller dismissViewControllerAnimated:YES completion:nil];
}