IOS开发基础知识--碎片11
1:AFNetwork判断网络状态
#import “AFNetworkActivityIndicatorManager.h" - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //网络 [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; [[AFNetworkReachabilityManager sharedManager] startMonitoring]; //网络状态判断 [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { switch (status) { case AFNetworkReachabilityStatusNotReachable:{ [self showMBPHudTipStr:@"当前无网络连接"]; break; } case AFNetworkReachabilityStatusReachableViaWiFi:{ [LogUtil logUtilstring:@"WiFi网络"]; break; } case AFNetworkReachabilityStatusReachableViaWWAN:{ [self showMBPHudTipStr:@"无线网络"]; break; } default: break; } }]; return YES; }
2:UIButton倒计时
当在倒计时uibutton不能被响应事件; -(void)startTime{ __block int timeout=60; //倒计时时间 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue); dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行 dispatch_source_set_event_handler(_timer, ^{ if(timeout<=0){ //倒计时结束,关闭 dispatch_source_cancel(_timer); dispatch_async(dispatch_get_main_queue(), ^{ //设置界面的按钮显示 根据自己需求设置 [self.againBtn setTitle:@"重发验证码" forState:UIControlStateNormal]; self.againBtn.userInteractionEnabled = YES; self.labNoMessage.text=@"没有收到验证码吗?"; self.labNoMessage.textColor=[UIColor redColor]; }); }else{ int seconds = timeout % 60; NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds]; dispatch_async(dispatch_get_main_queue(), ^{ //设置界面的按钮显示 根据自己需求设置 [self.againBtn setTitle:[NSString stringWithFormat:@"重发激活邮件(%@)",strTime] forState:UIControlStateNormal]; self.againBtn.userInteractionEnabled = NO; self.labNoMessage.text=@"激活邮件发送成功"; self.labNoMessage.textColor=[UIColor colorWithHexString:@"84BF20"]; }); timeout--; } }); dispatch_resume(_timer); }
3:判断iphone设备
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) #define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) #define IS_RETINA ([[UIScreen mainScreen] scale] >= 2.0) #define SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width) #define SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height) #define SCREEN_MAX_LENGTH (MAX(SCREEN_WIDTH, SCREEN_HEIGHT)) #define SCREEN_MIN_LENGTH (MIN(SCREEN_WIDTH, SCREEN_HEIGHT)) #define IS_IPHONE_4_OR_LESS (IS_IPHONE && SCREEN_MAX_LENGTH < 568.0) #define IS_IPHONE_5 (IS_IPHONE && SCREEN_MAX_LENGTH == 568.0) #define IS_IPHONE_6 (IS_IPHONE && SCREEN_MAX_LENGTH == 667.0) #define IS_IPHONE_6P (IS_IPHONE && SCREEN_MAX_LENGTH == 736.0)
4:在IOS8以下报一个自动布局的BUG,而在IOS8却能正常运行
会导致APP挂掉,BUG内容: Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘Auto Layout still required after executing -layoutSubviews.
UITableView’s implementation of -layoutSubviews needs to call super.’ - (void)layoutSubviews { //自动布局的内容放在super layoutSubviews前面 [self _updateConstraints]; [super layoutSubviews]; }
5:与JS交互,并把JS代码兼容android跟IOS
JS代码: $(function () { var u = navigator.userAgent, app = navigator.appVersion; var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器 var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端 if (isAndroid) { $('#btn_Success').attr('href', 'javascript:mailActive.backHome()'); } else if (isiOS) { $('#btn_Success').attr('href', 'protoclo://backHome'); } }); 而IOS则是shouldStartLoadWithRequest: -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *newURL=[[request URL] absoluteString]; if([newURL hasPrefix:@"protoclo://"]) { NSArray *stringArray=[newURL componentsSeparatedByString:@"//"]; if (stringArray.count>1&&[[stringArray objectAtIndex:1] isEqualToString:@"backHome"]) { [self webJavascriptBackHome]; } } return YES; } 注:比较好IOS的JS交互第三方插件WebViewJavascriptBridge[不错的关于如何使用这个插件的说明:http://www.henishuo.com/webviewjavascriptbridge-detail-use/];在IOS开发调试内嵌webView时可以用Safari进行调试,它可以设置出开发模式菜单,开发->ios simulator 就可以实现查看网页的运行详情(Safari->偏好设置-高级-在菜单中显示“开发”);
如果IOS要调用JS的方法可以使用stringByEvaluatingJavaScriptFromString 如下实例
IOS代码:
- (IBAction)sdfsdfsdf:(id)sender {
[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"getMessageFromApp('%@')", @"加载结束调sdfsdf用方法"]];
}
Html代码:
<script type="text/javascript">
function getMessageFromApp(message){
var testDiv = document.getElementById("testDiv");
testDiv.innerText = message;
}
</script>
6:FMDB使用的一点心得:数据库创建、制表、查询等以及image转换成二进制nsdata保存到数据库中
首先,获取数据库的路径,(如果不存在,就是我们想要存储的路径),不用担心每次都创建数据库会重复,不会的,如果没有则创建,有了就不会再重复创建;
接下来,我们要制表,首先我们先查看我们的表是否已经存在,方法在下面代码中;如果存在则跳过,不存在则创建
-(void)DataBaseInit { //获取Document文件夹下的数据库文件,没有则创建 NSString *dbPath = [self getDBPath]; FMDatabase *membersDB = [FMDatabase databaseWithPath:dbPath]; if (![membersDB open]) { NSLog(@"open membersDB failed"); return; } //监测数据库中我要需要的表是否已经存在 NSString *existsSql = [NSString stringWithFormat:@"select count(name) as countNum from sqlite_master where type = 'table' and name = '%@'", @"Member" ]; FMResultSet *rs = [membersDB executeQuery:existsSql]; if ([rs next]) { NSInteger count = [rs intForColumn:@"countNum"]; NSLog(@"The table count: %li", count); if (count == 1) { NSLog(@"log_keepers table is existed."); return; } NSLog(@"log_keepers is not existed."); //创建表 //[membersDB executeUpdate:@"CREATE TABLE PersonList (Name text, Age integer, Sex integer,Phone text, Address text, Photo blob)"]; [membersDB executeUpdate:@"CREATE TABLE Member (Name text, Age integer, Sex integer,Height integer, Weight integer, Photo blob)"]; } [rs close]; } -(NSString *)getDBPath { NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *DBPath = [documentPath stringByAppendingPathComponent:@"members.db"];//成员列表数据库 return DBPath; }
下面是数据成员的添加,不过我首先检查数据库中我要建的成员是否已经存在,避免重复添加
-(void)doneAction:(UIButton *)button { //保存到数据库 membersDB //获取Document文件夹下的数据库文件,没有则创建 NSString *dbPath = [self getDBPath]; FMDatabase *membersDB = [FMDatabase databaseWithPath:dbPath]; if (![membersDB open]) { NSLog(@"open membersDB failed"); return; } //返回数据库中第一条满足条件的结果 //select count(name) as countNum from sqlite_master where type = 'table' and name = '%@'", @"log_keepers FMResultSet *rs =[membersDB executeQuery:@"SELECT COUNT(Name) AS countNum FROM Member WHERE Name = ?",self.nameTextField.text]; while ([rs next]) { NSInteger count = [rs intForColumn:@"countNum"]; NSLog(@"countNum == %i",count); if (count > 0) { // NSLog(@"你要创建的成员,已经创建同名的!"); //下面这个是我用的第三方库,用来提醒,很方便,不用,注释掉即可 _noticeView = [[GCDiscreetNotificationView alloc]initWithText:@"成员已经保存 或者 同名成员已存在!" showActivity:YES inPresentationMode:GCDiscreetNotificationViewPresentationModeTop inView:self.view ]; [_noticeView showAndDismissAutomaticallyAnimated]; } else { //出入数据:刚健的成员添加进去 //插入数据 NSData *imageData = UIImagePNGRepresentation(self.iconImageView.image);//将png图片转化为nsdata BOOL insert = [membersDB executeUpdate:@"INSERT INTO Member (Name, Age, Sex, Height, Weight, Photo) VALUES (?,?,?,?,?,?)",self.nameTextField.text,[NSNumber numberWithInteger:[self.ageTextField.text integerValue]],[NSNumber numberWithInteger:self.sex] ,[NSNumber numberWithInteger:[self.heightTextField.text integerValue]],[NSNumber numberWithInteger:[self.weightTextField.text integerValue]], imageData]; if (insert) { NSLog(@"添加成员成功!!"); } } } //关闭数据库 [membersDB close]; }