How to check for request time out , is there a notification I can set? - iphone

I want to check for whether the request has timed out after some period.
I know NSNotifiactionCenter ,but don't know how to set the request time out notification for it.
thanks.

You could just use a timer and cancel your notification request if not received by then?
e.g. taking Apple's reachability example:
- (void) startNotifier
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(onReachabilityChanged:) name:#"kNetworkReachabilityChangedNotification" object:nil];
notified = NO;
[self performSelector:#selector(onRequestTimeout) withObject:nil afterDelay:5.0]; // 5 secs
}
- (void)onReachabilityChanged:(NSNotification *)note
{
// Do whatever on notification
notified = YES;
}
- (void) onRequestTimeout
{
if (!notified)
{
// Do whatever on request timeout
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"kNetworkReachabilityChangedNotification" object:nil];
}
}

Related

Resume AVPlayer video playback after app become active

I write custom player from AVPlayer for video playback. According to Apple docs set the video layer:
self.player = [IPLPlayer new];
self.player.playerLayer = (AVPlayerLayer *)self.playerView.layer;
Where self.playerView is usual class from those docs:
#implementation PlayerView
+ (Class) layerClass {
return [AVPlayerLayer class];
}
- (AVPlayer *)player {
return [(AVPlayerLayer *)[self layer] player];
}
- (void)setPlayer:(AVPlayer *) player {
[(AVPlayerLayer *) [self layer] setPlayer:player];
}
The problem is:
When close app (Home button), or block screen, the video playback is stopped, and when resume ONLY audio playback resumed, the image on screen is still those was before block screen - it's fully static and note change frames.
How to resume VIDEO playing after screen is blocked?
Seems I must to register notifications, and after app become active resume video layer:
-(void)registerNotification
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(willEnterBackground)
name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(didEnterForeground)
name:UIApplicationDidBecomeActiveNotification object:nil];
}
-(void)unregisterNotification
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)willEnterBackground
{
NSLog(#"willEnterBackground");
[self.playerView willEnterBackground];
}
-(void)didEnterForeground
{
NSLog(#"didEnterForeground");
[self.playerView didEnterForeground];
}
And one solution that binds all this information together.
Maybe player status should be handled differently, but I like the recursive way.
Note: If you do not need the exact seek time, you can use [_player seekToTime:<#(CMTime)#> completionHandler:<#^(BOOL finished)completionHandler#>] It's faster but it seeks to the nearest key frame.
- (void)viewDidLoad
{
[super viewDidLoad];
....
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(appEnteredForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(appEnteredBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
}
-(void)viewWillDisappear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}
....
-(void) appEnteredForeground {
AVPlayerLayer *player = (AVPlayerLayer *)[playerView layer];
[player setPlayer:NULL];
[player setPlayer:_player];
[self playAt:currentTime];
}
-(void) appEnteredBackground {
[_player pause];
currentTime = [_player currentTime];
}
-(void)playAt: (CMTime)time {
if(_player.status == AVPlayerStatusReadyToPlay && _player.currentItem.status == AVPlayerItemStatusReadyToPlay) {
[_player seekToTime:time toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {
[_player play];
}];
} else {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self playAt:time];
});
}
}
This works for me on Swift 3
Add somewhere while setting up the view:
NotificationCenter.default.addObserver(self,
selector: #selector(appWillEnterForegroundNotification),
name: .UIApplicationWillEnterForeground, object: nil)
Grab your player and force it to play:
func appWillEnterForegroundNotification() {
myPlayer.play()
}
Don't forget to remove the observers when you don't need them:
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
Use the UIApplicationWillEnterForegroundNotification as well. That way you know your app will be active and visible to the user:
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(appEnteredForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
The trick is to detach all video layers from their players when the app did enter background and reattaching them when the app did become active again.
So in your -applicationDidEnterBackground: you got to trigger a mechanism that results in
avPlayerLayer.player = nil;
and in your -applicationDidBecomeActive: you reattach the player like
avPlayerLayer.player = self.avPlayer;
Also have a look at this Tech Note (QA1668) from Apple.
After some research I've found, that the same bag is in iOS player (WebBrowser, MPMoviePlayerController). May be because distribution type of content is Progressive Download.
So solution is:
Use below notifications and save current time.
After app is resumed, recreate AVPlayer and start playing from saved
time.
In all other cases image is blocked, or view become black.

NSNotification not receiving in View Controller from appDelegate

hello i assign nsnotifiaction in app delegate.m's method and this method call eprox every 30sec, and i wants its notifcation in viewcontroller adn execute method,
here is my code of appdelegate .m
- (void)layoutAnimated:(BOOL)animated{
BOOL yy= self.bannerView.bannerLoaded;
if (yy==1){
self.iAdString=[NSMutableString stringWithString:#"1"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"BannerViewActionWillBegin" object:self];
}
else{
self.iAdString=[NSMutableString stringWithString:#"0"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"BannerViewActionDidFinish" object:self];
}
}
and in viewcontroller.m
//i defined in viewdidload method
- (void)viewDidLoad{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(willBeginBannerViewActionNotification:) name:#"BannerViewActionWillBegin "object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(didFinishBannerViewActionNotification:) name:#"BannerViewActionDidFinish" object:nil];
}
its method are..
- (void)willBeginBannerViewActionNotification:(NSNotification *)notification{
[self.view addSubview:self.app.bannerView];
NSLog(#"come");
}
- (void)didFinishBannerViewActionNotification:(NSNotification *)notification {
NSLog(#"come");
[self.app.bannerView removeFromSuperview];
}
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
I have not getting response of excessing method while method read in appdelegate file.
Please help me.
You have a typo error.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(willBeginBannerViewActionNotification:) name:#"BannerViewActionWillBegin "object:nil];
//Your error here-------------------------------------------------------------------------------------------------------------------------------------^
You have put a space there.
SideNote: For all notification names, you should/can create a separate file and put all your notification names as constants strings.
const NSString *kBannerViewActionWillBegin=#"BannerViewActionWillBegin";
this will be easier to change the value and no such typo will happen.
From your code what I get is except for the notification name's all other stuff is fine, did you check whether the notification gets fired. Try keeping break points at the notification firing line.

How to send object in NSNotification?

I want to send object to selector in NSNotification.I mean, I have 3 buttons and on click of each button I am registering notification and when that event occurred I am calling one selector and in that selector I want to find out which button user has clicked because I have common action for all 3 buttons.
-(void)allThreeButtonAction:(sender)id
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(performSomeOperationWhenEventOccur) name:#"EventCompletedNotification" object:nil];
}
//Some event occurred, so I am sending notification
[[NSNotificationCenter defaultCenter] postNotificationName:#"EventCompletedNotification" object:nil];
//Notified method
-(void)performSomeOperationWhenEventOccur
{
//Here I want to know which button is pressed.
}
I hope I am clear.
You may want to look at postNotificationName:object:userInfo: from NSNotificationCenter documentation
You simply send a UserInfo containing whatever you need to identify the button (easiest is the pointer to the button) that you retrieve in your selector.
Your selector signature should receive the notification:
- (void)performSomeOperationWhenEventOccur:(NSNotification*) notification:(NSNotification*) notification
{
// Use [notification userInfo] to determine which button was pressed...
}
Don't forget to modify the selector name when your register it:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(performSomeOperationWhenEventOccur:) name:#"EventCompletedNotification" object:nil];
You can't pass an object when adding a notification observer, so you'll have to store the button that was pressed somewhere:
-(void)allThreeButtonAction:(id)sender
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(performSomeOperationWhenEventOccur) name:#"EventCompletedNotification" object:nil];
self.buttonPressed = sender;
}
Then you can just read it in your notification handler:
-(void)performSomeOperationWhenEventOccur
{
if ( self.buttonPressed = self.button1 )
...
}
Below Snippet will help you.
Button1
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(performSomeOperationWhenEventOccur:) name:#"button1" object:button1];
Button2
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(performSomeOperationWhenEventOccur:) name:#"button2" object:button2];
Change method to following
- (void) performSomeOperationWhenEventOccur:(NSNotification *) notification
{
if ([[notification name] isEqualToString:#"button1"])
{
NSButton *button1=[notification button1];
NSLog (#"Successfully received the test notification! from button1");
}
else
{
NSButton *button2=[notification button2];
NSLog (#"Successfully received the test notification! from button2");
}
}

Does NSNotification work everywhere?

I'm sending a notification using:
[[NSNotificationCenter defaultCenter] postNotificationName:#"historyLoaded" object:jsonReturn];
And receiving the notification using:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(manageHistory:) name:#"historyLoaded" object:nil];
Then the method in the selector is:
- (void) manageHistory: (NSNotification *) historyData{
NSLog(#"this bit of code was run");
}
For some reaason the notification doesn't get through. Can notifications be send and received from anywhere in the app?
The object parameter in postNotification should be filled with an object which is "sending" the notification, or nil if the sender is not necessarily specified.
If you want to pass some information along, you should use postNotificationName:object:userInfo and put the information in userInfo dictionary instead.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(manageHistory) name:#"historyLoaded" object:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"historyLoaded"
object:nil userInfo:jsonReturn];
- (void) manageHistory: (NSNotification *) historyData{
NSDictionary* _dict = historyData.userInfo;
NSLog(#"Your information embedded to dictiuonary obj %#",_dict);
}
NOTE : Make sure your historyData should be a dictionary object in postNotificationName

Is it possible to check if done button is pressed

I have notification on movie player:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];
And it's handler:
- (void) moviePlayBackDidFinish:(NSNotification*)notification
{
[[UIApplication sharedApplication] setStatusBarHidden:YES];
// Remove observer
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];
[self dismissModalViewControllerAnimated:YES];
}
Here in this handler method I want to check if the done button is sender. Because I have two senders to this method. How ti check this?
Per docs: MPMoviePlayerPlaybackDidFinishNotification userInfo dictionary must contain NSNUmber for MPMoviePlayerPlaybackDidFinishReasonUserInfoKey key indicating the reason playback has finished. Its possible values:
enum {
MPMovieFinishReasonPlaybackEnded,
MPMovieFinishReasonPlaybackError,
MPMovieFinishReasonUserExited
};
You will first need to assign tag to your buttons before the action and then check the value of the sender tag.
Just add these lines of code:
- (void) moviePlayBackDidFinish:(NSNotification*)notification {
NSInteger anyInteger = [sender tag];
//Now check the value of the anyInteger and write the code accordingly.
//switch case or if condition whatever you want.
}
That's it.
This is an old thread but I stumbled upon it while looking for a solution, and the accepted solution doesn't show the final code.
Here is what you have to do:
- (void) moviePlayBackDidFinish:(NSNotification*)notification
{
NSLog(#"moviePlayBackDidFinish");
// Remove observer
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];
NSInteger movieFinishReason= [[[notification userInfo]objectForKey:
MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];
if(movieFinishReason == 2 || movieFinishReason == 1 || movieFinishReason == 0){
[self dismissViewControllerAnimated:YES completion:nil];
}
/*
MPMovieFinishReasonPlaybackEnded = 0,//played movie sucessfuly.
MPMovieFinishReasonPlaybackError = 1, //error in playing movie
MPMovieFinishReasonUserExited = 2; //user quitting the application / user pressed done button
*/
}
Add tag with the button and put condition according to the tag.
Or check by
if([sender isEqual:btn1])
{
}
else
{
}