Identify number of incoming call in iPhone - iphone

How do I know who is calling me?
Identify the number or even the contact in my list case I have.
I can identify if have or not a call, with this code.
void (^ctCallStateMuda)(NSNotification *) = ^(NSNotification * notification) {
NSString *callInfo = [[notification userInfo] objectForKey:#"callState"];
if ([callInfo isEqualToString:CTCallStateIncoming]) {
NSLog(#">>>>>> chegando");
} else if ([callInfo isEqualToString:CTCallStateConnected]) {
NSLog(#">>> atendendo <<<");
} else if ([callInfo isEqualToString:CTCallStateDisconnected]) {
NSLog(#"desconectado >>>>>>");
} else if ([callInfo isEqualToString:CTCallStateConnected]) {
NSLog(#"discando");
} else {
NSLog(#"nada");
}
};
CTCallCenter *callCenter;
callCenter = [[CTCallCenter alloc] init];
callCenter.callEventHandler = ^(CTCall* aCallIncomming) {
NSDictionary *dict = [NSDictionary dictionaryWithObject:aCallIncomming.callState
forKey:#"callState"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"CTCallStateDidChange"
object:self
userInfo:dict];
};
[[NSNotificationCenter defaultCenter] addObserverForName:#"CTCallStateDidChange"
object:nil
queue:nil
usingBlock:ctCallStateMuda];

You don't have access to this information in the public SDK (a jailbroken iPhone is another matter). Apple prohibit apps from having access to any information relating to call history. The code you've posted above is so your app can detect when the user is receiving a phone call and adapt their interface accordingly, but that's it.

Related

Adding MBProgressHud to MPMoviePlayerController

I am trying to show MBProgressHud to MPMoviePlayerController, for that I am observing notifications for load states of MPMoviePlayer, but somehow Method observing notification never observes notifications for load states other then MPMovieLoadStatePlayable. I show MBProgressHud when video starts streaming but it does not work after it plays and then to pause to download video, Due to this I am unable to engage user while video is loading, If anyone has a better method please mention it or if there is any problem in the following code then let me know.
-(void)movieLoadStateDidChange:(NSNotification*)notification{
MPMoviePlayerController *player = [notification object];
if ((player.loadState & MPMovieLoadStatePlayable) == MPMovieLoadStatePlayable) {
NSLog(#"Load state Playable");
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}else if ((player.loadState & MPMovieLoadStatePlaythroughOK) == MPMovieLoadStatePlaythroughOK){
NSLog(#"Load state Playing");
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}else if ((player.loadState & MPMovieLoadStateStalled) == MPMovieLoadStateStalled){
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
NSLog(#"Load state stalled");
}else if ((player.loadState & MPMovieLoadStateUnknown) == MPMovieLoadStateUnknown){
NSLog(#"Load State unknown");
}
}
Ok .. i got your problem and the problem is that you are not getting notification for load states except MPMovieLoadStatePlayable. so here what you can do is...like below...
write down below notifiations in viewdidload
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlayerPlaybackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlayerPlaybackStateDidChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlayerLoadStateDidChange:) name:MPMoviePlayerLoadStateDidChangeNotification object:nil];
After defining it in ViewDidLoad , implement those functions like below....
- (void) moviePlayerPlaybackDidFinish:(NSNotification *)notification
{
//your code....
MPMovieFinishReason finishReason = [notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] integerValue];
NSError *error = notification.userInfo[XCDMoviePlayerPlaybackDidFinishErrorUserInfoKey];
NSString *reason = #"Unknown";
switch (finishReason)
{
case MPMovieFinishReasonPlaybackEnded:
reason = #"Playback Ended";
break;
case MPMovieFinishReasonPlaybackError:
reason = #"Playback Error";
break;
case MPMovieFinishReasonUserExited:
reason = #"User Exited";
break;
}
NSLog(#"Finish Reason: %#%#", reason, error ? [#"\n" stringByAppendingString:[error description]] : #"");
}
- (void) moviePlayerPlaybackStateDidChange:(NSNotification *)notification
{
MPMoviePlayerController *moviePlayerController = notification.object;
NSString *playbackState = #"Unknown";
switch (moviePlayerController.playbackState)
{
case MPMoviePlaybackStateStopped:
playbackState = #"Stopped";
break;
case MPMoviePlaybackStatePlaying:
playbackState = #"Playing";
break;
case MPMoviePlaybackStatePaused:
playbackState = #"Paused";
break;
case MPMoviePlaybackStateInterrupted:
playbackState = #"Interrupted";
break;
case MPMoviePlaybackStateSeekingForward:
playbackState = #"Seeking Forward";
break;
case MPMoviePlaybackStateSeekingBackward:
playbackState = #"Seeking Backward";
break;
}
NSLog(#"Playback State: %#", playbackState);
}
- (void) moviePlayerLoadStateDidChange:(NSNotification *)notification
{
MPMoviePlayerController *moviePlayerController = notification.object;
NSMutableString *loadState = [NSMutableString new];
MPMovieLoadState state = moviePlayerController.loadState;
if (state & MPMovieLoadStatePlayable)
[loadState appendString:#" | Playable"];
if (state & MPMovieLoadStatePlaythroughOK)
[loadState appendString:#" | Playthrough OK"];
if (state & MPMovieLoadStateStalled)
[loadState appendString:#" | Stalled"];
NSLog(#"Load State: %#", loadState.length > 0 ? [loadState substringFromIndex:3] : #"N/A");
}
let me know it is working or not!!!
Happy Coding!!!!

[NSConcreteNotification isReachable]: unrecognized selector sent to instance

I'm trying to get ASIReachability to work in my app which works when the connection isn't there but when the connection exists it give the following error:
2013-04-08 12:26:20.501 Your Llanelli Companion[1576:207] -[NSConcreteNotification isReachable]: unrecognized selector sent to instance 0x7d84d30
I can't seem to remedy this and it's beginning to bug me.
.m file:
- (void) CheckIfAInternetConnectionExists
{
Reachability *reach = [[Reachability reachabilityWithHostName:#"http://176.31.101.181:8020/listen.pls"]retain ];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
[reach startNotifier];
}
- (void) reachabilityChanged:(Reachability *)reach {
if ([reach isReachable ]) {
NSLog(#"connection");
ServerFound = YES;
[self PrepareStream];
} else{
NSLog(#"no connection");
ServerFound = NO;
[self PrepareStream];
}
}
If someone can figure this out for me I'd be very grateful.
When you receive the notification, the parameter to your reachabilityChanged: method will be the notification itself. To get the Reachability object, you'll need to get it from the notification by sending -[NSNotification object] to the notification.
So something like this should work:
- (void) reachabilityChanged:(NSNotification *)note {
Reachability *reach = [note object];
if ([reach isReachable ]) {
NSLog(#"connection");
ServerFound = YES;
} else{
NSLog(#"no connection");
ServerFound = NO;
}
[self PrepareStream];
}

Handle ACAccountStoreDidChangeNotification for Facebook & Twitter in iOS 6+

I am using Social framework for Facebook & Twitter integration. For this I followed this link
Everything is working fine except when I app receives ACAccountStoreDidChangeNotification , it crashes.
App crashes when
1) I installed app for first time & user don't have Facebook / Twitter account configured in Settings.
2) When I call any method of Facebook / Twitter , it gives me error code 6 as I don't have account configured which is right.
3) I click on HOME button so my app enters background & add account in Settigs.
4) Once I configured account & come back to app , my app launches from background & receives ACAccountStoreDidChangeNotification.
5) In selector of ACAccountStoreDidChangeNotification my account object is nil so my app crashes. So I checked for the nil
Here is my code
#pragma mark - Request Facebook Account Access
-(void)requestFacebookAccountAccess
{
requestType = kNoOpRequest;
// Register for Account Change notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(accountChanged:) name:ACAccountStoreDidChangeNotification object:nil];
self.accountStore = [[ACAccountStore alloc]init];
ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
// Set facebook permissions
NSArray *permissions = nil;
// We need to ask for Basic permission first
if (![kUserDefaults boolForKey:FACEBOOK_BASIC_PERMISSION]) {
permissions = #[#"email",#"user_about_me",#"user_location",#"friends_about_me"];
self.isBasicFacebookPermissionsRequested = YES;
}
else {
permissions = #[#"email",#"user_about_me",#"user_location",#"friends_about_me",#"publish_stream"];
}
//use ACAccountStore to help create your dictionary
NSDictionary *dictFacebook = #{
ACFacebookAppIdKey: kFacebookAppIDKey,
ACFacebookPermissionsKey: permissions,
ACFacebookAudienceKey: ACFacebookAudienceFriends
};
[self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFacebook completion:^(BOOL granted, NSError *error) {
if (granted) {
if (self.isBasicFacebookPermissionsRequested) {
self.isBasicFacebookPermissionsRequested = NO;
[kUserDefaults saveBasicFacebookPermissionsGrantedStatus:YES];
//[self requestFacebookAccountAccess];
}
// User granted permission to Accout
NSArray *accountsArray = [self.accountStore accountsWithAccountType:FBaccountType];
if ([accountsArray count]>0) {
//It will always be the last object with SSO
self.facebookAccount = [accountsArray lastObject];
NSLog(#"In %s::IS MAIN THREAD:- %#",__PRETTY_FUNCTION__,[NSThread isMainThread]?#"YES":#"NO");
if ([self.delegate respondsToSelector:#selector(didFacebookAccountAccessGranted)]) {
dispatch_async(dispatch_get_main_queue(),^{
[self.delegate didFacebookAccountAccessGranted];
});
}
}
else {
[self showAlertWithTitle:#"Error" andMessage:#"You don't have any Facebook accounts set up yet.Please set a Facebbok account and try again."];
}
}
else {
DLog(#"User denied permission to Accout::Localized Error:- %#",error.localizedDescription);
if([error code]==6) {
[self showAlertWithTitle:#"Error" andMessage:#"Please setup facebook account from Settings"];
if ([self.delegate respondsToSelector:#selector(didFacebookAccountAccessDenied:)]) {
dispatch_async(dispatch_get_main_queue(),^{
[self.delegate didFacebookAccountAccessDenied:error];
});
}
}
else if ([self.delegate respondsToSelector:#selector(didFacebookAccountAccessDenied:)]) {
dispatch_async(dispatch_get_main_queue(),^{
[self.delegate didFacebookAccountAccessDenied:error];
});
}
else {
// User denied permission to Account
[self showAlertWithTitle:#"Error" andMessage:[NSString stringWithFormat:#"User denied permission to Accout::Error:- %#",error.localizedDescription]];
}
}
}];
}
#pragma mark - Get Logged In User Info
-(void)getLoggedInUserInfo
{
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/fql"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"SELECT current_location,uid,name,sex,birthday,email,pic FROM user WHERE uid=me()",#"q", nil];
requestType = kGetLoggedInUserInfoRequest;
[self requestDataUsingURL:requestURL parameters:dict requestMethod:SLRequestMethodGET];
}
#pragma mark - Request Data From Facebook
-(void)requestDataUsingURL:(NSURL*)requestURL parameters:(NSDictionary*)params requestMethod:(SLRequestMethod)reuqestMethod
{
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:reuqestMethod
URL:requestURL
parameters:params];
request.account = self.facebookAccount;
[request performRequestWithHandler:^(NSData *data,
NSHTTPURLResponse *response,
NSError *error)
{
NSDictionary *dictData =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(!error)
{
if([dictData objectForKey:#"error"]!=nil)
{
DLog(#"Request Data From Facebook Errro:- %#",dictData);
[self attemptRenewCredentials];
if ([self.delegate respondsToSelector:#selector(didGetFacebookError:)]) {
dispatch_async(dispatch_get_main_queue(),^{
[self.delegate didGetFacebookError:dictData];
});
}
}
else {
// Process the response
//NSLog(#"Response Dictionary contains: %#", dictData );
if ([self.delegate respondsToSelector:#selector(didPostToFacebook:)]) {
dispatch_async(dispatch_get_main_queue(),^{
[self.delegate didPostToFacebook:dictData];
});
}
}
}
else{
if ([self.delegate respondsToSelector:#selector(didGetFacebookError:)]) {
dispatch_async(dispatch_get_main_queue(),^{
[self.delegate didGetFacebookError:dictData];
});
}
else {
[self showAlertWithTitle:#"Error" andMessage:#"Some error occured while processing Facebook request"];
}
}
}];
}
-(void)accountChanged:(NSNotification *)notif
{
if (self.facebookAccount!=nil) {
[self attemptRenewCredentials];
}
else {
[self requestFacebookAccountAccess];
}
}
#pragma mark - Attempt to Renew Credentials
-(void)attemptRenewCredentials
{
[self.accountStore renewCredentialsForAccount:(ACAccount *)self.facebookAccount completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){
if(!error)
{
switch (renewResult) {
case ACAccountCredentialRenewResultRenewed:
NSLog(#"Good to go");
[self againRequestFacebook];
break;
case ACAccountCredentialRenewResultRejected:
NSLog(#"User declined permission");
break;
case ACAccountCredentialRenewResultFailed:
NSLog(#"non-user-initiated cancel, you may attempt to retry");
break;
default:
break;
}
}
else{
//handle error gracefully
NSLog(#"error from renew credentials%#",error);
}
}];
}
-(void)againRequestFacebook
{
switch (requestType) {
case kGetLoggedInUserInfoRequest:
[self getLoggedInUserInfo];
break;
case kGetFriendsInfoRequest:
[self getFacebookFriendsInfo];
break;
case kPostToWallRequest:
[self postToFacebookWallInBackgroundForUserId:fbUserIdForPost withParams:paramsToPost];
break;
default:
break;
}
}
#pragma mark - Remove Observer for Notification
-(void)dealloc
{
requestType = kNoOpRequest;
[[NSNotificationCenter defaultCenter] removeObserver:ACAccountStoreDidChangeNotification];
}
But accountChanged method gets called multiple times.
What is wrong in this ? How can I handle this situation ?
Any kind of help is highly appreciated.
Thanks in advance.
I am facing the same problem...so i used a work around by having a BOOL value in NSUserDefaults to execute accountChanged method only once
-(void)accountChanged:(NSNotification *)notif
{
BOOL calledAccountChanged =[[[NSUserDefaults standardUserDefaults] objectForKey:DidAccountChanged] boolValue];
if(!calledAccountChanged)
{
if (self.facebookAccount!=nil) {
[self attemptRenewCredentials];
}
else {
[self requestFacebookAccountAccess];
}
}
}
Then we can change DidAccountChanged value later in the code...
If you have better solution do post it...

AVQueuePlayer Video Image Freeze, Silenced Notification

I am building a AVQeueue Player from a set of encoded videos on an s3 bucket, playing videos in sequence using AVPlayerActionAtItemEndAdvance;
videos are all encoded the same resolution and codec
They are all tested good to play
On some devices this solution below works fine
The issue below is noticed both on IOS 5.x and 6.x
Been trying to check all done in the main thread. (most likely the issue)
Issue: on the simulator and on some devices (noticed on 4s and 5) after an x amount of videos (x being unpredictable at times but usually 3, 4) a video plays only with sound and kills the queue and does not throw "playerItemDidReachEnd" notification. App does not crash or freeze.
No Errors received from "AVPlayerItemStatusFailed" or "AVPlayerItemStatusUnknown"
If anyone has experience with this problem please share.
Code:
-(void)addObservers {
dispatch_async(dispatch_get_main_queue(),
^{
for(int i = 0; i < [self.videodata count]; i++) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:[self.videodata objectAtIndex:i]];
[[self.videodata objectAtIndex:i] addObserver:self forKeyPath:#"status" options:NSKeyValueObservingOptionNew context:nil];
[[self.videodata objectAtIndex:i] addObserver:self forKeyPath:#"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
[[self.videodata objectAtIndex:i] addObserver:self forKeyPath:#"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];
}
});
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *) change context:(void *)context
{
if ([object isKindOfClass:[AVPlayerItem class]])
{
AVPlayerItem *item = (AVPlayerItem *)object;
if ([keyPath isEqualToString:#"status"])
{ //yes->check it...
switch(item.status)
{
case AVPlayerItemStatusFailed:
{
[TestFlight passCheckpoint:#"AV FAILED"];
NSError *error = [item error];
NSLog(#"playback error is %#", error);
break;
}
case AVPlayerItemStatusReadyToPlay:
NSLog(#"player item status is ready to play");
break;
case AVPlayerItemStatusUnknown:
{
[TestFlight passCheckpoint:#"AV STATUS UNKNOWN"];
break;
}
}
}
else if (item == [self.queuePlayer currentItem] && [keyPath isEqualToString:#"playbackBufferEmpty"])
{
if (item.playbackBufferEmpty)
{
[loadingView show:YES];
}
}
else if(item == [self.queuePlayer currentItem] && [keyPath isEqualToString:#"playbackLikelyToKeepUp"])
{
[self.queuePlayer play];
[loadingView hide:YES];
}
}
}
- (void)playerItemDidReachEnd:(NSNotification *)notification {
NSLog(#"ended video %i " , (int)self.currentItem);
AVPlayerItem *p = [notification object];
[p seekToTime:kCMTimeZero];
}

Get launch options without overriding didFinishLaunchingWithOptions:

I'm embedded in an environment (Adobe AIR) where I cannot override didFinishLaunchingWithOptions. Is there any other way to get those options? Are they stored in some global variable somewhere? Or does anyone know how to get those options in AIR?
I need this for Apple Push Notification Service (APNS).
Following the path in the link Michiel left ( http://www.tinytimgames.com/2011/09/01/unity-plugins-and-uiapplicationdidfinishlaunchingnotifcation/ ), you can create a class who's init method adds an observer to the UIApplicationDidFinishLaunchingNotification key. When the observer method is executed, the launchOptions will be contained in the notification's userInfo. I was doing this with local notifications so this was the implementation of my class:
static BOOL _launchedWithNotification = NO;
static UILocalNotification *_localNotification = nil;
#implementation NotificationChecker
+ (void)load
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(createNotificationChecker:)
name:#"UIApplicationDidFinishLaunchingNotification" object:nil];
}
+ (void)createNotificationChecker:(NSNotification *)notification
{
NSDictionary *launchOptions = [notification userInfo] ;
// This code will be called immediately after application:didFinishLaunchingWithOptions:.
UILocalNotification *localNotification = [launchOptions objectForKey: #"UIApplicationLaunchOptionsLocalNotificationKey"];
if (localNotification)
{
_launchedWithNotification = YES;
_localNotification = localNotification;
}
else
{
_launchedWithNotification = NO;
}
}
+(BOOL) applicationWasLaunchedWithNotification
{
return _launchedWithNotification;
}
+(UILocalNotification*) getLocalNotification
{
return _localNotification;
}
#end
Then when my extension context is initialized I check the NotificationChecker class to see if the application was launched with a notification.
BOOL appLaunchedWithNotification = [NotificationChecker applicationWasLaunchedWithNotification];
if(appLaunchedWithNotification)
{
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
UILocalNotification *notification = [NotificationChecker getLocalNotification];
NSString *type = [notification.userInfo objectForKey:#"type"];
FREDispatchStatusEventAsync(context, (uint8_t*)[#"notificationSelected" UTF8String], (uint8_t*)[type UTF8String]);
}
Hope that helps someone!