我有一个音乐播放器应用程序,我正在检查应用程序运行时的互联网连接。当连接消失时,我正在显示警告消息并停止播放歌曲。如果连接恢复,我再次播放歌曲而没有用户在其中做任何事情,但问题是我无法在再次播放歌曲时隐藏警报。这是代码:
#import "FirstViewController.h"
CM_EXPORT const CMTime kCMTimeZero;
@interface FirstViewController ()
@end
@implementation FirstViewController
@synthesize metadatas;
@synthesize toggleButton;
@synthesize slider;
@synthesize mpVolumeView = _mpVolumeView;
@synthesize viewVolume;
- (void)viewDidLoad
{
toggleIsOn=TRUE;
MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:self.viewVolume.bounds] ;
[self.viewVolume addSubview:volumeView];
[volumeView sizeToFit];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(IBAction)playButtonPressed:(id)sender
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:TRUE forKey:@"FirstPlay"];
[defaults setBool:YES forKey:@"alertShown"];
if(toggleIsOn){
toggleIsOn=!toggleIsOn;
player = nil;
NSString *stringurl = @"";
stringurl = @"http://majestic.wavestreamer.com:6221/listen.pls";
NSURL *url = [NSURL URLWithString:stringurl];
asset = [AVURLAsset URLAssetWithURL:url options:nil];
playerItem = [AVPlayerItem playerItemWithAsset:asset];
player = [AVPlayer playerWithPlayerItem:playerItem];
player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
[playerItem addObserver:self forKeyPath:@"timedMetadata" options:NSKeyValueObservingOptionNew context:nil];
[playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
[player play];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(audioSessionInterrupted:) name:AVAudioSessionInterruptionNotification object:nil];
[self.toggleButton setImage:[UIImage imageNamed:@"reload.png"] forState:UIControlStateNormal];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
else {
[self.toggleButton setImage:[UIImage imageNamed:@"playMusic.png"] forState:UIControlStateNormal];
self->player.rate=0.0;
toggleIsOn=!toggleIsOn;
}
}
- (void)audioSessionInterrupted:(NSNotification *)notification
{
NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey];
NSNumber *interruptionOption = [[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey];
switch (interruptionType.unsignedIntegerValue) {
case AVAudioSessionInterruptionTypeBegan:{
// [self.toggleButton setImage:[UIImage imageNamed:@"playMusic.png"] forState:UIControlStateNormal];
// • Audio has stopped, already inactive
// • Change state of UI, etc., to reflect non-playing state
} break;
case AVAudioSessionInterruptionTypeEnded:{
// • Make session active
// • Update user interface
// • AVAudioSessionInterruptionOptionShouldResume option
if (interruptionOption.unsignedIntegerValue == AVAudioSessionInterruptionOptionShouldResume) {
// Here you should continue playback.
[player play];
}
} break;
default:
break;
}
}
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)audioPlayer
{
[player pause];
}
-(void)audioRecorderEndInterruption:(AVAudioRecorder *)audioPlayer
{
[player play];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:TRUE forKey:@"alertShown"];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
internetReachable = [Reachability reachabilityForInternetConnection];
[internetReachable startNotifier];
// check if a pathway to a random host exists
hostReachable = [Reachability reachabilityWithHostName:@"www.apple.com"];
[hostReachable startNotifier];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context {
[playerItem removeObserver:self forKeyPath:keyPath];
if ([keyPath isEqualToString:@"status"]) {
AVPlayerItem *pItem = (AVPlayerItem *)object;
if (pItem.status == AVPlayerItemStatusReadyToPlay)
{
metadatas.text = @"";
}
}
if ([keyPath isEqualToString:@"timedMetadata"]) {
for (AVAssetTrack *track in playerItem.tracks) {
for (AVPlayerItemTrack *item in player.currentItem.tracks) {
if ([item.assetTrack.mediaType isEqual:AVMediaTypeAudio]) {
NSArray *meta = [playerItem timedMetadata];
for (AVMetadataItem *metaItem in meta) {
NSString *source = metaItem.stringValue;
metadatas.text = source;
}
}
}
}
}
[self.toggleButton setImage:[UIImage imageNamed:toggleIsOn ? @"playMusic.png" :@"stop.png"] forState:UIControlStateNormal];
}
-(IBAction)fbButtonPressed:(id)sender
{
NSURL *url = [NSURL URLWithString:@"http://www.facebook.com"];
if (![[UIApplication sharedApplication] openURL:url])
NSLog(@"%@%@",@"Failed to open url:",[url description]);
}
-(IBAction)inButtonPressed:(id)sender
{
NSURL *url = [NSURL URLWithString:@"http://www.linkedin.com"];
if (![[UIApplication sharedApplication] openURL:url])
NSLog(@"%@%@",@"Failed to open url:",[url description]);
}
-(IBAction)tweetButtonPressed:(id)sender
{
NSURL *url = [NSURL URLWithString:@"http://www.twitter.com"];
if (![[UIApplication sharedApplication] openURL:url])
NSLog(@"%@%@",@"Failed to open url:",[url description]);
}
-(IBAction) sliderChanged:(id)sender
{
}
-(void) checkNetworkStatus:(NSNotification *)notice
{
// called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
switch (internetStatus)
{
case NotReachable:
{
NSLog(@"The internet is down.");
NSLog(@"%d",[defaults boolForKey:@"alertShown"]);
BOOL isAlertShown = [defaults boolForKey:@"alertShown"];
if(isAlertShown)
{
[self showAlert];
}
break;
}
case ReachableViaWiFi:
{
NSLog(@"The internet is working via WIFI.");
BOOL isFirstTimePlayed = [defaults boolForKey:@"FirstPlay"];
if(isFirstTimePlayed)
{
[self playButtonPressed:nil];
}
break;
}
case ReachableViaWWAN:
{
NSLog(@"The internet is working via WWAN.");
[self playButtonPressed:nil];
break;
}
}
}
-(void)showAlert
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:FALSE forKey:@"alertShown"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Alert" message: @"You have lost data connectivity. Please wait while we try to establish the connection again." delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
- (NSUInteger)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskPortrait;
}
@end
答案 0 :(得分:3)
在方法showAlert
中,您引用了UIAlertView
对象alert
。只需将该引用保存在属性中,以便以后可以访问它。
@interface FirstViewController ()
@property (nonatomic, strong) UIAlertView* internetConnectivityAlertView;
@end
-(void)showAlert
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:FALSE forKey:@"alertShown"];
self.internetConnectivityAlertView = [[UIAlertView alloc] initWithTitle:@"Alert"
message:@"You have lost data connectivity. Please wait while we try to establish the connection again."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[self.internetConnectivityAlertView show];
}
当您获得互联网连接时,只需致电
if(self.internetConnectivityAlertView)
{
[self.internetConnectivityAlertView dismissWithClickedButtonIndex:0 animated:YES];
self.internetConnectivityAlertView = nil;
}
取消警报。
请参阅UIAlertView的API文档。