最后更新时间:2018-03-27
一、常用方法
1.字符串方法
1.1判断字符串是否包含另一字符串
//判断字符是否包含某字符串;
NSString*string =@"hello,shenzhen,martin";
//字条串是否包含有某字符串
if([string rangeOfString:@"martin"].location ==NSNotFound)
{
NSLog(@"string 不存在 martin");
}else{
NSLog(@"string 包含 martin");
}
//字条串开始包含有某字符串
if([string hasPrefix:@"hello"])
{
NSLog(@"string 包含 hello");
}else{
NSLog(@"string 不存在 hello");
}
//字符串末尾有某字符串;
if([string hasSuffix:@"martin"]) {
NSLog(@"string 包含 martin");
}else{
NSLog(@"string 不存在 martin");
}
在iOS8以后,还可以用下面的方法来判断是否包含某字符串:
//在iOS8中你可以这样判断
NSString*str =@"hello world";
if([str containsString:@"world"]) {
NSLog(@"str 包含 world");
}else{
NSLog(@"str 不存在 world");
}
1.2字符串大小写转换(可包含其他字符)
NSString*test =@"test";
NSString*testUp = [test uppercaseString];//大写
NSString*testUpFirst = [test capitalizedString];//开头大写,其余小写
NSString*TEACHER =@"TEACHER";
NSString*TEACHERLower = [TEACHER lowercaseString];//小写
NSString*TEACHERUpFirst = [TEACHE RcapitalizedString];//开头大写,其余小写
1.3分割字符串,并将其存放在数组内
NSString*string =@"sdfsfsfsAdfsdf";
NSArray *array = [string componentsSeparatedByString:@"A"]; //从字符A中分隔成2个元素的数组
NSLog(@"array:%@",array); //结果是adfsfsfs和dfsdf
2.获取沙盒文件全路径
/** 获取沙盒文件全路径*/
-(NSString *)BSGGetSandBoxFilePathWithFileName:(NSString *)FileName
{
//获取沙盒路径
NSArray * pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * sandBoxPath = pathArray[0];
//获取文件全路径
NSString * filePath = [sandBoxPath stringByAppendingPathComponent:FileName];
return filePath;
}
以下方法获取bundle下(即工程里的plist文件内容)
NSString * bundlePath = [[NSBundle mainBundle]pathForResource:@"test" ofType:@"plist"];
NSMutableDictionary * preData = [[NSMutableDictionary alloc]initWithContentsOfFile:bundlePath];
3.获取年月日字符串
/** 获取年月日字符串*/
- (NSString *)BSGGetDate
{
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYYMMdd"];
NSString * DateTime = [formatter stringFromDate:date];
return DateTime;
}
4.开启网络连接
NSAppTransportSecurity——dictionary
NSAllowsArbitraryLoads——yes
5.UIView设置半透明后不影响其上子控件透明度的方法
self.view.backgroundColor= [[UIColor grayColor] colorWithAlphaComponent:0.5];
通过这种方法设置透明度不会影响加载在其上的控件的透明度
6.UITextField设置最长长度方法
//此处设最大编辑长度为30
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(textField == self.TheTextField) {
//这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
if(range.length == 1 && string.length == 0) {
returnYES;
}
else if(self.TheTextField.text.length >= 30) {
self.TheTextField.text = [textField.text substringToIndex:30];
returnNO;
}
}
returnYES;
}
来源:仅几行iOS代码限制TextField输入长度
7.直接回退到根控制器的方法
/** 回退到根控制器*/
-(void)dismissToRootViewController
{
UIViewController *vc = self;
while (vc.presentingViewController) {
vc = vc.presentingViewController;
}
[vc dismissViewControllerAnimated:YES completion:nil];
}
例子(推送):
A->B->C
则A是B的presentingViewController,即A == B.presentingViewController;
C是B的presentedViewController,即C == B.presentedViewController;
该方法找到了当前控制器的根控制器,后直接将其所有的presentedViewController全部dismiss掉
8.获取AppDelegate的实例
AppDelegate *aPPDelegateVC = [[UIApplication sharedApplication] delegate];
9.获取地图CLLocationCoordinate2D坐标
CLLocationCoordinate2D loc = CLLocationCoordinate2DMake(26.08, 119.28);
10.获取当前时间的链接
http://api.k780.com:88/?app=life.time&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
11.返回主线程方法
dispatch_async(dispatch_get_main_queue(), ^{
//返回主线程
});
12.定位设置
NSLocationWhenInUseUsageDescription
获取定位权限
NSLocationAlwaysUsageDescription
获取定位权限
NSLocationAlwaysAndWhenInUseUsageDescription
获取后台定位权限
iOS11后使用以下:
NSLocationWhenInUseUsageDescription
获取定位权限
NSLocationAlwaysAndWhenInUseUsageDescription
获取后台定位权限
13.保持图片不渲染
- 通过代码设置
[theImage imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)]
- 直接在对应图片的属性设置
AlwaysOriginal
14.通过图片的URL地址,从网络上获取图片
-(UIImage *) BSGGetImageFromURL:(NSString *)fileURL{
UIImage * result;
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
result = [UIImage imageWithData:data];
return result;
}
15. 从相册获取图片
实现两个代理:
代码:
//头像-从相册获取
- (IBAction)doAvatar:(UIButton *)sender {
// 1.判断相册是否可以打开
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
// 2. 创建图片选择控制器
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
/**
typedef NS_ENUM(NSInteger, UIImagePickerControllerSourceType) {
UIImagePickerControllerSourceTypePhotoLibrary, // 相册
UIImagePickerControllerSourceTypeCamera, // 用相机拍摄获取
UIImagePickerControllerSourceTypeSavedPhotosAlbum // 相簿
}
*/
// 3. 设置打开照片相册类型(显示所有相簿)
ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
// ipc.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
// 照相机
// ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
// 4.设置代理
ipc.delegate = self;
// 5.modal出这个控制器
[self presentViewController:ipc animated:YES completion:nil];
}
#pragma mark - 协议
// 获取图片后的操作
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// 销毁控制器
[picker dismissViewControllerAnimated:YES completion:nil];
// 设置图片
UIImage * image = info[UIImagePickerControllerOriginalImage];
[_avatarImageView setImage:image];
}
16.打电话
- 方法1:
NSMutableString *str=[[NSMutableString alloc]initWithFormat:@"tel:%@",driveNumber];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
- 方法2:
NSMutableString* str=[[NSMutableString alloc]initWithFormat:@"telprompt://%@",driveNumber];
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:str]];
参考链接:iOS 拨打电话四种方式总结(推荐最后一种)
17.发短信
[[UIApplicationsharedApplication]openURL:[NSURLURLWithString:@"sms://13888888888"]];
参考链接:iOS调用系统发短信的两种方法
18.移除某页面上的所有控件
[[XXX subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
19. 移除当前视图下的所有子控件
[view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
- 视图也可以为控件,一样可以用来移除控件上的控件
20.倒计时方式
方法一(线程)
//计时器
-(void)sentPhoneCodeTimeMothed
{
//倒计时时间
__block NSInteger 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_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
if (timeOut <= 0) {
dispatch_source_cancel(timer);
//主线程设置样式
dispatch_async(dispatch_get_main_queue(), ^{
[_codeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
[_codeBtn setUserInteractionEnabled:YES];
});
}else{
//开始计时
NSInteger seconds = timeOut % 60;
NSString *strTime = [NSString stringWithFormat:@"%.1ld",seconds];
dispatch_async(dispatch_get_main_queue(), ^{
[_codeBtn setTitle:[NSString stringWithFormat:@"已发送(%@)",strTime] forState:UIControlStateNormal];
[_codeBtn setUserInteractionEnabled:NO];
});
timeOut --;
}
});
dispatch_resume(timer);
}
21.
二、界面相关
1.0获取手机相册内图片或调用摄像机拍照
设置代理:
-(void)doAvatar:(UIButton *)sender
{
UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
UIAlertAction * cancerAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
[alertController addAction:cancerAction];
UIAlertAction * photoAction = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
[self OpenCamera:self];
}];
[alertController addAction:photoAction];
UIAlertAction * albumAction = [UIAlertAction actionWithTitle:@"打开相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
[self OpenPhotos:self];
}];
[alertController addAction:albumAction];
[self presentViewController:alertController animated:YES completion:nil];
}
- (void)OpenCamera:(id)sender {
//当前设备是否可以打开摄像头
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
//创建摄像头管理者
UIImagePickerController * picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
//指定调用资源为摄像头
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:picker animated:YES completion:nil];
}
}
- (void)OpenPhotos:(id)sender {
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
//创建摄像头管理者
UIImagePickerController * picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
//指定调用资源为摄像头
[picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:picker animated:YES completion:nil];
}
}
//负责保存照相机照的图片
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//将图片保存至相册
//获取当前相机拍摄的照片
UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData * imageData = UIImagePNGRepresentation(image);
[userdefaults setObject:imageData forKey:@"头像"];
[avatarButton setImage:image forState:(UIControlStateNormal)];
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
//将照片写入到本地相册当中
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
[self dismissViewControllerAnimated:YES completion:nil];
}
2.0获取相册内照片时得到对应图片名
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// 销毁控制器
[picker dismissViewControllerAnimated:YES completion:nil];
// 获取图片
UIImage * image = info[UIImagePickerControllerOriginalImage];
//获取本地图片名
NSURL * imagePathURL = info[UIImagePickerControllerImageURL];
NSString * imagePath = [imagePathURL absoluteString];
NSArray * oneArray = [imagePath componentsSeparatedByString:@"/"];
NSString * imageName = oneArray.lastObject;
//图片处理
}
-
UIImagePickerControllerImageURL
属性在iOS 11以后出现
3.
三、App及相关系统方法
1.0判断当前App的名称和版本号
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
CFShow(infoDictionary);
// app名称
NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
// app版本
NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
// app build版本
NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
//手机序列号
NSString* identifierNumber = [[UIDevice currentDevice] uniqueIdentifier];
NSLog(@"手机序列号: %@",identifierNumber);
//手机别名: 用户定义的名称
NSString* userPhoneName = [[UIDevice currentDevice] name];
NSLog(@"手机别名: %@", userPhoneName);
//设备名称
NSString* deviceName = [[UIDevice currentDevice] systemName];
NSLog(@"设备名称: %@",deviceName );
//手机系统版本
NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
NSLog(@"手机系统版本: %@", phoneVersion);
//手机型号
NSString* phoneModel = [[UIDevice currentDevice] model];
NSLog(@"手机型号: %@",phoneModel );
//地方型号 (国际化区域名称)
NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel];
NSLog(@"国际化区域名称: %@",localPhoneModel );
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
// 当前应用名称
NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
NSLog(@"当前应用名称:%@",appCurName);
// 当前应用软件版本 比如:1.0.1
NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
NSLog(@"当前应用软件版本:%@",appCurVersion);
// 当前应用版本号码 int类型
NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
NSLog(@"当前应用版本号码:%@",appCurVersionNum);
2.0判断客户端是iPhone或iPad
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_PAD (UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPad)
3.0获取网络运营商
//获取网络运营商
+(NSString *)CTTelephonyNetworkProviders
{
//获取本机运营商名称
CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
CTCarrier *carrier = [info subscriberCellularProvider];
//当前手机所属运营商名称
NSString *mobile;
//先判断有没有SIM卡,如果没有则不获取本机运营商
if (!carrier.isoCountryCode) {
// NSLog(@"没有SIM卡");
mobile = @"无运营商";
}else{
mobile = [carrier carrierName];
}
return mobile;
}
- 使用:
[self CTTelephonyNetworkProviders]
4.0 调用系统分享功能(如多图分享)
内容可以不只是图片。图片分享可以分享至微信和QQ
查询微信多图分享时发现微信SDK未开放多图分享功能,只能调用系统方法进行分享
//多图分享
UIImage *imageToShare1 = [UIImage imageNamed:@"01"];
UIImage *imageToShare2 = [UIImage imageNamed:@"02"];
UIImage *imageToShare3 = [UIImage imageNamed:@"03"];
NSArray *activityItems = @[imageToShare1,imageToShare2,imageToShare3];
UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
[self presentViewController:activityVC animated:TRUE completion:nil];
链接