有用的代码
1. 遍历NavigationController栈中的视图
XXView *rootViewController = nil;
for (UIViewController *VC in self.navigationController.viewControllers) {
if ([VC isKindOfClass:[XXView class]]) {
rootViewController = (XXView *)VC;
}
}
[self.navigationController popToViewController:rootViewController animated:YES];
2. 背景音乐播放,支持mp3格式
需要先导入框架及代码中#import <AVFoundation/AVFoundation.h>
NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"backgrounmusic" ofType:@"mp3"];
NSURL *url = [[NSURL alloc] initFileURLWithPath:musicPath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
// 创建播放器
self.myBackMusic = player; //赋值给自己定义的类变量
[url release];
[player release];
[myBackMusic prepareToPlay];
[myBackMusic setVolume:1];
myBackMusic.numberOfLoops = -1; //设置音乐播放次数 -1为一直循环
if(mainMusicStatus)
{
[myBackMusic play]; //播放
}
3. 按钮播放声音、播放短声音
需要导入框架#import <AudioToolbox/AudioToolbox.h>
NSString *thesoundFilePath = [[NSBundle mainBundle] pathForResource:@"Clap Crowd" ofType:@"caf"]; //音乐文件路径
CFURLRef thesoundURL = (CFURLRef)[NSURL fileURLWithPath:thesoundFilePath];
AudioServesCreateSystemSoundID(thesoundURL, &sameViewSoundID);
//变量SoundID与URL对应
AudioServicesPlaySystemSound(sameViewSoundID); //播放SoundID声音
4. 判断网络是否连接
/***
* 此函数用来判断是否网络连接服务器正常
* 需要导入Reachability类
*/
+ (BOOL)isExistenceNetwork
{
BOOL isExistenceNetwork;
Reachability *reachability = [Reachability reachabilityWithHostName:@""]; // 测试服务器状态
switch([reachability currentReachabilityStatus]) {
case NotReachable:
isExistenceNetwork = FALSE;
break;
case ReachableViaWWAN:
isExistenceNetwork = TRUE;
break;
case ReachableViaWiFi:
isExistenceNetwork = TRUE;
break;
}
return isExistenceNetwork;
}
5. 实时通知网络状况
/*
* 在应用委托的方法didFinishLaunchingWithOptions中添加
*/
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
reachability = [[Reachability reachabilityWithHostName:@"www.baidu.com"] retain];
[reachability startNotifier];
........
return YES;
/**
*此函数通过判断联网方式,通知给用户
*/
- (void)reachabilityChanged:(NSNotification *)notification
{
Reachability *curReachability = [notification object];
NSParameterAssert([curReachability isKindOfClass:[Reachability class]]);
NetworkStatus curStatus = [curReachability currentReachabilityStatus];
if(curStatus == NotReachable) {
[DOIN_Util logFax:@"连接失败"];
}
}
6. 延时函数和Timer的使用
//延时函数:
[NSThread sleepForTimeInterval:5.0]; //暂停5s.
//Timer的使用:
NSTimer *connectionTimer; //timer对象
//实例化timer
self.connectionTimer=[NSTimerscheduledTimerWithTimeInterval:1.5 target:selfselector:@selector(timerFired:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop]addTimer:self.connectionTimer forMode:NSDefaultRunLoopMode];
//用timer作为延时的一种方法
do{
[[NSRunLoopcurrentRunLoop]runUntilDate:[NSDatedateWithTimeIntervalSinceNow:1.0]];
}while(!done);
//timer调用函数
-(void)timerFired:(NSTimer *)timer{
done =YES;
}