最后更新時(shí)間:2018-03-27
一苟耻、常用方法
1.字符串方法
1.1判斷字符串是否包含另一字符串
//判斷字符是否包含某字符串吨枉;
NSString*string =@"hello,shenzhen,martin";
//字條串是否包含有某字符串
if([string rangeOfString:@"martin"].location ==NSNotFound)
{
NSLog(@"string 不存在 martin");
}else{
NSLog(@"string 包含 martin");
}
//字條串開(kāi)始包含有某字符串
if([string hasPrefix:@"hello"])
{
NSLog(@"string 包含 hello");
}else{
NSLog(@"string 不存在 hello");
}
//字符串末尾有某字符串桐款;
if([string hasSuffix:@"martin"]) {
NSLog(@"string 包含 martin");
}else{
NSLog(@"string 不存在 martin");
}
在iOS8以后,還可以用下面的方法來(lái)判斷是否包含某字符串:
//在iOS8中你可以這樣判斷
NSString*str =@"hello world";
if([str containsString:@"world"]) {
NSLog(@"str 包含 world");
}else{
NSLog(@"str 不存在 world");
}
1.2字符串大小寫轉(zhuǎn)換(可包含其他字符)
NSString*test =@"test";
NSString*testUp = [test uppercaseString];//大寫
NSString*testUpFirst = [test capitalizedString];//開(kāi)頭大寫,其余小寫
NSString*TEACHER =@"TEACHER";
NSString*TEACHERLower = [TEACHER lowercaseString];//小寫
NSString*TEACHERUpFirst = [TEACHE RcapitalizedString];//開(kāi)頭大寫杠览,其余小寫
1.3分割字符串俏讹,并將其存放在數(shù)組內(nèi)
NSString*string =@"sdfsfsfsAdfsdf";
NSArray *array = [string componentsSeparatedByString:@"A"]; //從字符A中分隔成2個(gè)元素的數(shù)組
NSLog(@"array:%@",array); //結(jié)果是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文件內(nèi)容)
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.開(kāi)啟網(wǎng)絡(luò)連接
NSAppTransportSecurity——dictionary
NSAllowsArbitraryLoads——yes
5.UIView設(shè)置半透明后不影響其上子控件透明度的方法
self.view.backgroundColor= [[UIColor grayColor] colorWithAlphaComponent:0.5];
通過(guò)這種方法設(shè)置透明度不會(huì)影響加載在其上的控件的透明度
6.UITextField設(shè)置最長(zhǎng)長(zhǎng)度方法
//此處設(shè)最大編輯長(zhǎng)度為30
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(textField == self.TheTextField) {
//這里的if時(shí)候?yàn)榱双@取刪除操作,如果沒(méi)有次if會(huì)造成當(dāng)達(dá)到字?jǐn)?shù)限制后刪除鍵也不能使用的后果.
if(range.length == 1 && string.length == 0) {
returnYES;
}
else if(self.TheTextField.text.length >= 30) {
self.TheTextField.text = [textField.text substringToIndex:30];
returnNO;
}
}
returnYES;
}
來(lái)源:僅幾行iOS代碼限制TextField輸入長(zhǎng)度
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户矢;
該方法找到了當(dāng)前控制器的根控制器,后直接將其所有的presentedViewController全部dismiss掉
8.獲取AppDelegate的實(shí)例
AppDelegate *aPPDelegateVC = [[UIApplication sharedApplication] delegate];
9.獲取地圖CLLocationCoordinate2D坐標(biāo)
CLLocationCoordinate2D loc = CLLocationCoordinate2DMake(26.08, 119.28);
10.獲取當(dāng)前時(shí)間的鏈接
http://api.k780.com:88/?app=life.time&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
11.返回主線程方法
dispatch_async(dispatch_get_main_queue(), ^{
//返回主線程
});
12.定位設(shè)置
<key>NSLocationWhenInUseUsageDescription</key>
<string>獲取定位權(quán)限</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>獲取定位權(quán)限</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>獲取后臺(tái)定位權(quán)限</string>
iOS11后使用以下:
<key>NSLocationWhenInUseUsageDescription</key>
<string>獲取定位權(quán)限</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>獲取后臺(tái)定位權(quán)限</string>
13.保持圖片不渲染
- 通過(guò)代碼設(shè)置
[theImage imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)]
- 直接在對(duì)應(yīng)圖片的屬性設(shè)置
AlwaysOriginal
14.通過(guò)圖片的URL地址殉疼,從網(wǎng)絡(luò)上獲取圖片
-(UIImage *) BSGGetImageFromURL:(NSString *)fileURL{
UIImage * result;
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
result = [UIImage imageWithData:data];
return result;
}
15. 從相冊(cè)獲取圖片
實(shí)現(xiàn)兩個(gè)代理:<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
代碼:
//頭像-從相冊(cè)獲取
- (IBAction)doAvatar:(UIButton *)sender {
// 1.判斷相冊(cè)是否可以打開(kāi)
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
// 2. 創(chuàng)建圖片選擇控制器
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
/**
typedef NS_ENUM(NSInteger, UIImagePickerControllerSourceType) {
UIImagePickerControllerSourceTypePhotoLibrary, // 相冊(cè)
UIImagePickerControllerSourceTypeCamera, // 用相機(jī)拍攝獲取
UIImagePickerControllerSourceTypeSavedPhotosAlbum // 相簿
}
*/
// 3. 設(shè)置打開(kāi)照片相冊(cè)類型(顯示所有相簿)
ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
// ipc.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
// 照相機(jī)
// ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
// 4.設(shè)置代理
ipc.delegate = self;
// 5.modal出這個(gè)控制器
[self presentViewController:ipc animated:YES completion:nil];
}
#pragma mark - 協(xié)議<UIImagePickerControllerDelegate>
// 獲取圖片后的操作
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
// 銷毀控制器
[picker dismissViewControllerAnimated:YES completion:nil];
// 設(shè)置圖片
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]];
17.發(fā)短信
[[UIApplicationsharedApplication]openURL:[NSURLURLWithString:@"sms://13888888888"]];
18.移除某頁(yè)面上的所有控件
[[XXX subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
19. 移除當(dāng)前視圖下的所有子控件
[view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
- 視圖也可以為控件梯浪,一樣可以用來(lái)移除控件上的控件
20.倒計(jì)時(shí)方式
方法一(線程)
//計(jì)時(shí)器
-(void)sentPhoneCodeTimeMothed
{
//倒計(jì)時(shí)時(shí)間
__block NSInteger timeOut = 60;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//計(jì)時(shí)器
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);
//主線程設(shè)置樣式
dispatch_async(dispatch_get_main_queue(), ^{
[_codeBtn setTitle:@"重新獲取" forState:UIControlStateNormal];
[_codeBtn setUserInteractionEnabled:YES];
});
}else{
//開(kāi)始計(jì)時(shí)
NSInteger seconds = timeOut % 60;
NSString *strTime = [NSString stringWithFormat:@"%.1ld",seconds];
dispatch_async(dispatch_get_main_queue(), ^{
[_codeBtn setTitle:[NSString stringWithFormat:@"已發(fā)送(%@)",strTime] forState:UIControlStateNormal];
[_codeBtn setUserInteractionEnabled:NO];
});
timeOut --;
}
});
dispatch_resume(timer);
}
21.
二、界面相關(guān)
1.0獲取手機(jī)相冊(cè)內(nèi)圖片或調(diào)用攝像機(jī)拍照
設(shè)置代理:<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
-(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:@"打開(kāi)相冊(cè)" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
[self OpenPhotos:self];
}];
[alertController addAction:albumAction];
[self presentViewController:alertController animated:YES completion:nil];
}
- (void)OpenCamera:(id)sender {
//當(dāng)前設(shè)備是否可以打開(kāi)攝像頭
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
//創(chuàng)建攝像頭管理者
UIImagePickerController * picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
//指定調(diào)用資源為攝像頭
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:picker animated:YES completion:nil];
}
}
- (void)OpenPhotos:(id)sender {
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
//創(chuàng)建攝像頭管理者
UIImagePickerController * picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
//指定調(diào)用資源為攝像頭
[picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:picker animated:YES completion:nil];
}
}
//負(fù)責(zé)保存照相機(jī)照的圖片
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
//將圖片保存至相冊(cè)
//獲取當(dāng)前相機(jī)拍攝的照片
UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData * imageData = UIImagePNGRepresentation(image);
[userdefaults setObject:imageData forKey:@"頭像"];
[avatarButton setImage:image forState:(UIControlStateNormal)];
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
//將照片寫入到本地相冊(cè)當(dāng)中
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
[self dismissViewControllerAnimated:YES completion:nil];
}
2.0獲取相冊(cè)內(nèi)照片時(shí)得到對(duì)應(yīng)圖片名
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)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以后出現(xiàn)
3.
三瓢娜、App及相關(guān)系統(tǒng)方法
1.0判斷當(dāng)前App的名稱和版本號(hào)
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"];
//手機(jī)序列號(hào)
NSString* identifierNumber = [[UIDevice currentDevice] uniqueIdentifier];
NSLog(@"手機(jī)序列號(hào): %@",identifierNumber);
//手機(jī)別名: 用戶定義的名稱
NSString* userPhoneName = [[UIDevice currentDevice] name];
NSLog(@"手機(jī)別名: %@", userPhoneName);
//設(shè)備名稱
NSString* deviceName = [[UIDevice currentDevice] systemName];
NSLog(@"設(shè)備名稱: %@",deviceName );
//手機(jī)系統(tǒng)版本
NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
NSLog(@"手機(jī)系統(tǒng)版本: %@", phoneVersion);
//手機(jī)型號(hào)
NSString* phoneModel = [[UIDevice currentDevice] model];
NSLog(@"手機(jī)型號(hào): %@",phoneModel );
//地方型號(hào) (國(guó)際化區(qū)域名稱)
NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel];
NSLog(@"國(guó)際化區(qū)域名稱: %@",localPhoneModel );
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
// 當(dāng)前應(yīng)用名稱
NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
NSLog(@"當(dāng)前應(yīng)用名稱:%@",appCurName);
// 當(dāng)前應(yīng)用軟件版本 比如:1.0.1
NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
NSLog(@"當(dāng)前應(yīng)用軟件版本:%@",appCurVersion);
// 當(dāng)前應(yīng)用版本號(hào)碼 int類型
NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
NSLog(@"當(dāng)前應(yīng)用版本號(hào)碼:%@",appCurVersionNum);
2.0判斷客戶端是iPhone或iPad
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_PAD (UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPad)
3.0獲取網(wǎng)絡(luò)運(yùn)營(yíng)商
//獲取網(wǎng)絡(luò)運(yùn)營(yíng)商
+(NSString *)CTTelephonyNetworkProviders
{
//獲取本機(jī)運(yùn)營(yíng)商名稱
CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
CTCarrier *carrier = [info subscriberCellularProvider];
//當(dāng)前手機(jī)所屬運(yùn)營(yíng)商名稱
NSString *mobile;
//先判斷有沒(méi)有SIM卡挂洛,如果沒(méi)有則不獲取本機(jī)運(yùn)營(yíng)商
if (!carrier.isoCountryCode) {
// NSLog(@"沒(méi)有SIM卡");
mobile = @"無(wú)運(yùn)營(yíng)商";
}else{
mobile = [carrier carrierName];
}
return mobile;
}
- 使用:
[self CTTelephonyNetworkProviders]
4.0 調(diào)用系統(tǒng)分享功能(如多圖分享)
內(nèi)容可以不只是圖片。圖片分享可以分享至微信和QQ
查詢微信多圖分享時(shí)發(fā)現(xiàn)微信SDK未開(kāi)放多圖分享功能眠砾,只能調(diào)用系統(tǒng)方法進(jìn)行分享
//多圖分享
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];