梵讯笔记

1.iOS9新特性:Bitcode

当运行之前的项目报错时,我们可以在”Build Settings”->”Enable Bitcode”中设置属性为NO

2.获取设备名字

[Device machineName]

3.获取沙盒Documents路径

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

 NSString *documentsDirectory = [paths objectAtIndex:0];
View Code

4.发短信方法

4.1openURL

[[UIApplication sharedApplication] openURL:@"sms:12345678"];
View Code

4.2MFMessageComposeViewController

首先在程序中导入MessageUI.framework。import头文件:#import "DeviceDetection.h"

然后在代码中使用下面的语句来调用短信发送窗口,并指定号码和短信内容:

MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
 controller.title = @"短信房源";
controller.body = HouseInfo;
controller.recipients = nil;
controller.messageComposeDelegate = self;
[self presentViewController:controller animated:YES completion:nil];
View Code

5.复制内容到剪切板

UIPasteboard *pasteboard =  [UIPasteboard generalPasteboard];
pasteboard.string = ResponseObj;
View Code

 6。iOS字符创中去除特殊字符串

NSInteger leftLength=[[leftStr stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length;
View Code

7.NSCharacterSet 简单用法

NSMutableCharacterSet *base = [NSMutableCharacterSet lowercaseLetterCharacterSet]; //字母
NSCharacterSet *decimalDigit = [NSCharacterSet decimalDigitCharacterSet];   //十进制数字
 [base formUnionWithCharacterSet:decimalDigit];    //字母加十进制
NSString *string = @"ax@d5s#@sfn$5`SF$$%x^(#e{]e";
//用上面的base隔开string然后组成一个数组,然后通过componentsJoinedByString,来连接成一个字符串
  NSLog(@"%@",[[string componentsSeparatedByCharactersInSet:base] componentsJoinedByString:@"-"]);
  [base invert];  //非 字母加十进制
  NSLog(@"%@",[[string componentsSeparatedByCharactersInSet:base] componentsJoinedByString:@"-"]);
答应结果:
 
 ax@d-s#@sfn$-`SF$$%x^(#e{]e
 
----5-------5--------------
View Code

 8.从系统选择多张图片

先导入库ELCImagePicker(第三方)

//从照片库
        if ([self shouldImage])
        {
            ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
            elcPicker.maximumImagesCount = 16-[images_ numberOfPhotos];
            elcPicker.returnsOriginalImage = NO;
            elcPicker.imagePickerDelegate = self;
            [self presentViewController:elcPicker animated:YES completion:nil];
        }else
        {
            UIAlertView *al=[[UIAlertView alloc]initWithTitle:@"权限受限" message:@"设置-手机梵讯-隐私" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [al show];
        }
View Code
#pragma mark ELCImagePickerController delegate
-(void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    NSString *imagePathDir;
    BOOL isSuccess = NO;
    for (NSDictionary *dict in info)
    {
        UIImage* img = [dict objectForKey:UIImagePickerControllerOriginalImage];
        
        imagePathDir = [[Util getHouseDirCurrentDateType] stringByReplacingOccurrencesOfString:@"_city_" withString:[YlwSingleMode shareDataModle].CityPinyin];
        //需要准备的数据
        NSString *PKHouseImageLite = [Util GetUUIDLite];
        NSString *PKHouseImage = [Util convertGuidSqlserverFromSqlite:PKHouseImageLite isClean:YES];
        NSString *imgType = @".jpg";

        CGSize sizeImageBig = [self getImageSize:img.size targetSize:CGSizeMake(600, 450)];
        CGSize sizeImageSmall = [self getImageSize:img.size targetSize:CGSizeMake(200, 150)];
        CGSize sizeImageIndex = [self getImageSize:img.size targetSize:CGSizeMake(80, 60)];
        
        UIImage *imgBig = [self reSizeImage:img toSize:sizeImageBig];
        UIImage *imgSmall = [self reSizeImage:img toSize:sizeImageSmall];
        UIImage *imgIndex = [self reSizeImage:img toSize:sizeImageIndex];
        
        
        imagePathDir=[imagePathDir stringByReplacingOccurrencesOfString:@"house/" withString:@"House/"];
        
        
        NSString *imagePathBig = [imagePathDir stringByAppendingPathComponent:[NSString stringWithFormat:@"house_%@_big.jpg",PKHouseImage]];
        NSString *imagePathSmall = [imagePathDir stringByAppendingPathComponent:[NSString stringWithFormat:@"house_%@_small.jpg",PKHouseImage]];
        NSString *imagePathIndex = [imagePathDir stringByAppendingPathComponent:[NSString stringWithFormat:@"house_%@_index.jpg",PKHouseImage]];
        
        NSData *imgBigData = UIImageJPEGRepresentation(imgBig, 0.3);
        NSData *imgSmallData = UIImageJPEGRepresentation(imgSmall, 0.3);
        NSData *imgIndexData = UIImageJPEGRepresentation(imgIndex, 0.3);
        
        NSInteger imgSize_Big = imgBigData.length;
        NSInteger imgSize_Small = imgSmallData.length;

        for (int i=0; i<3; i++) {
            [_houseImageCache storeImage:imgBig imageData:imgBigData forKey:imagePathBig toDisk:YES];
            i++;
            [_houseImageCache storeImage:imgSmall imageData:imgSmallData forKey:imagePathSmall toDisk:YES];
            i++;
            [_houseImageCache storeImage:imgIndex imageData:imgIndexData forKey:imagePathIndex toDisk:YES];

        }
      isSuccess = [self saveHouseImagesWith:PKHouseImageLite ImgPath:imagePathDir ImgType:imgType ImgSizeBig:imgSize_Big ImgSizeSmaill:imgSize_Small];
        [self houseimageNumber:nil];
    }
    if (isSuccess)
    {
        [ProgressHUD showSuccess:@"添加成功"];
        [picker dismissViewControllerAnimated:YES completion:nil];
        [self reloadSubviews];
    }
}
View Code
-(void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
     NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
     NSString *imagePathDir;
    BOOL isSuccess = NO;
    if ([mediaType isEqualToString:(NSString*)kUTTypeImage])
    {
        UIImage* img = [info objectForKey:UIImagePickerControllerOriginalImage];
        UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        imagePathDir = [[Util getHouseDirCurrentDateType] stringByReplacingOccurrencesOfString:@"_city_" withString:[YlwSingleMode shareDataModle].CityPinyin];
        //需要准备的数据
        NSString *PKHouseImageLite = [Util GetUUIDLite];
        NSString *PKHouseImage = [Util convertGuidSqlserverFromSqlite:PKHouseImageLite isClean:YES];
        NSString *imgType = @".jpg";
        
        CGSize sizeImageBig = [self getImageSize:img.size targetSize:CGSizeMake(600, 450)];
        CGSize sizeImageSmall = [self getImageSize:img.size targetSize:CGSizeMake(200, 150)];
        CGSize sizeImageIndex = [self getImageSize:img.size targetSize:CGSizeMake(80, 60)];
        
        UIImage *imgBig = [self reSizeImage:img toSize:sizeImageBig];
        UIImage *imgSmall = [self reSizeImage:img toSize:sizeImageSmall];
        UIImage *imgIndex = [self reSizeImage:img toSize:sizeImageIndex];
        
        
        imagePathDir=[imagePathDir stringByReplacingOccurrencesOfString:@"house/" withString:@"House/"];
        
        
        NSString *imagePathBig = [imagePathDir stringByAppendingPathComponent:[NSString stringWithFormat:@"house_%@_big.jpg",PKHouseImage]];
        NSString *imagePathSmall = [imagePathDir stringByAppendingPathComponent:[NSString stringWithFormat:@"house_%@_small.jpg",PKHouseImage]];
        NSString *imagePathIndex = [imagePathDir stringByAppendingPathComponent:[NSString stringWithFormat:@"house_%@_index.jpg",PKHouseImage]];
        
        NSData *imgBigData = UIImageJPEGRepresentation(imgBig, 0.3);
        NSData *imgSmallData = UIImageJPEGRepresentation(imgSmall, 0.3);
        NSData *imgIndexData = UIImageJPEGRepresentation(imgIndex, 0.3);
        
        NSInteger imgSize_Big = imgBigData.length;
        NSInteger imgSize_Small = imgSmallData.length;
        
        for (int i=0; i<3; i++) {
            [_houseImageCache storeImage:imgBig imageData:imgBigData forKey:imagePathBig toDisk:YES];
            i++;
            [_houseImageCache storeImage:imgSmall imageData:imgSmallData forKey:imagePathSmall toDisk:YES];
            i++;
            [_houseImageCache storeImage:imgIndex imageData:imgIndexData forKey:imagePathIndex toDisk:YES];
            
        }
        isSuccess = [self saveHouseImagesWith:PKHouseImageLite ImgPath:imagePathDir ImgType:imgType ImgSizeBig:imgSize_Big ImgSizeSmaill:imgSize_Small];
        [self houseimageNumber:nil];
        if (isSuccess)
        {
            [ProgressHUD showSuccess:@"添加成功"];
            [picker dismissViewControllerAnimated:YES completion:nil];
            [self reloadSubviews];
        }
    }
}
View Code
-(void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo{
        
    if (!error)
    {
        NSLog(@"保存有误");
    }
    else
    {
        NSLog(@"错误提示%@", error);
    }
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
View Code

9.判断是否支持拍照和相册

-(BOOL)shouldPhoto
{
    BOOL agree=NO;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized||authStatus == AVAuthorizationStatusNotDetermined)
    {
        agree=YES;
    }else
    {
        agree=NO;
    }
    return agree;
}
-(BOOL)shouldImage
{
    BOOL agree=NO;
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if(author == ALAuthorizationStatusAuthorized||author == ALAuthorizationStatusNotDetermined)
    {
        agree=YES;
    }else
    {
        agree=NO;
    }
    return agree;
}
View Code

10.上传图片

+(void)httpUploadHeadImage:(NSString *)Actio WithParam:(NSDictionary *)param success:(void(^)(id ResponseObject))Success Failure:(void (^)(id ResponseObject))Failure
{
    NSMutableDictionary *mDict = [NSMutableDictionary dictionary];
    if (param!=nil)
    {
        [mDict setDictionary:param];
    }
    AFHTTPRequestOperationManager * manager =[AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:Actio parameters:NULL constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
    {
        [formData appendPartWithFormData:[[NSString stringWithString:[mDict objectForKey:@"PKUser"]] dataUsingEncoding:NSUTF8StringEncoding] name:@"PKUser"];
        [formData appendPartWithFormData:[[NSString stringWithString:[mDict objectForKey:@"relPath"]] dataUsingEncoding:NSUTF8StringEncoding] name:@"relPath"];
        NSData * data=[NSData dataWithContentsOfFile:[mDict objectForKey:@"HeadBig"]];
        [formData appendPartWithFileData:data name:@"big" fileName:[mDict objectForKey:@"HadebigName"] mimeType: @"Image/jpep"];
        NSData * data1=[NSData dataWithContentsOfFile:[mDict objectForKey:@"Headsmall"]];
        
        [formData appendPartWithFileData:data1 name:@"small" fileName:[mDict objectForKey:@"HadesmallName"] mimeType: @"Image/png"];


    } success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSData * responseData = responseObject;
        NSString * responseStr =  [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
        Success(responseStr);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        
    }];
}
View Code

 11.设置导航栏属性

[self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor whiteColor], UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0 green:0.7 blue:0.8 alpha:1], UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)], UITextAttributeTextShadowOffset,
                                                                     [UIFont boldSystemFontOfSize:20], UITextAttributeFont,
                                                                     nil]];
View Code

12.设置分割线与距离(普通的tableView分割线短一些)

if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
View Code

 13.绘制图片

-(UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect =CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    CGContextFillRect(context, rect);
    
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
    
}
View Code

 14.NSJSONReadingMutableContainers:返回可变容器,NSMutableDictionary或NSMutableArray。 

NSJSONReadingMutableLeaves:返回的JSON对象中字符串的值为NSMutableString。

NSJSONReadingAllowFragments:允许JSON字符串最外层既不是NSArray也不是NSDictionary,但必须是有效的JSON Fragment。例如使用这个选项可以解析 @“123” 这样的字符串。

15.摇晃手机结束触发方法(系统声音与震动服务)

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (motion==UIEventSubtypeMotionShake)
    {
        [ProgressHUD show:LONDING];
        [self updateMyLocation];
    }
}
View Code
    SystemSoundID soundID;
    NSString *strSoundFile = [[NSBundle mainBundle] pathForResource:@"alertsound" ofType:@"wav"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:strSoundFile],&soundID);
    AudioServicesPlaySystemSound(soundID);
View Code
//公司代码   
 crash=kSystemSoundID_Vibrate;
    NSURL * shakeUrl = [[NSBundle mainBundle]URLForResource:@"shake_sound_male" withExtension:@"wav"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)shakeUrl, &crash);
View Code

 16.AFNetWorking检测网络状态代码

+(NSInteger)NetWorkType
{
    if (([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable))
    {
        return 0;
    }
    else if (([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable))
    {
        return 1;
    }
    else
    {
        return -1;
    }
    
}
View Code

 17.百度地图开启定位

_locService = [[BMKLocationService alloc]init];
_locService.delegate = self;
[_locService startUserLocationService];
View Code

 18.点击TextField以外的地方收回键盘

//先定义一个UIControl类型的对象,在上面可以添加触发事件,令SEL实践为回收键盘的方法,最后将UIControl的实例加到当前View上。
UIControl *m_control = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[m_control addTarget:self action:@selector(keyboardReturn) 
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:m_control];
 
- (void) keyboardReturn
{
[aTextField resignFirstResponder];
}
View Code

 19.tableView右侧索引

//viewDidLoad
_indexArr=[NSArray arrayWithObjects:@" ",@" ",@" ",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];


- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (issearch)
    {
        return nil;
    }else
    {
        return _indexArr;
//        return self.firstCharArray;
    }
}
View Code

 20.打开系统设置的方法

NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if ([[UIApplication sharedApplication] canOpenURL:url])
{
       [[UIApplication sharedApplication] openURL:url];
}
View Code

 21.取消第一响应者的方法

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [_bar resignFirstResponder];
}
View Code

 22.iOS生成唯一标识方法(使用CFUUIDRef 和CFStringRef)

+ (NSString *)GetUUID {
    CFUUIDRef theUUID = CFUUIDCreate(NULL);     
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);     
    CFRelease(theUUID);     
    return (__bridge_transfer NSString *)string ;
} 
View Code

23.UIView动画

[UIView beginAnimations:nil context:nil];
    if (_showLocalEmotion)
    {
        _toolBar.frame=CGRectMake(0, ScreenHeight-216-44-vhei, ScreenWidth, 44);
        self.tableView.frame=CGRectMake(0, 0, ScreenWidth, ScreenHeight-216-44-vhei);
    }else
    {
        _toolBar.frame = toolKeyboardDown;
        self.tableView.frame = tableKeyboardDown;
    }
    
    [UIView setAnimationDuration:0.7];
    [UIView commitAnimations];
View Code

 24.UIAlertView阻断键盘隐藏的解决办法

//键盘收缩动画时长为0.25秒,只需让代码延迟0.25秒执行
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //执行代码
        });
View Code
原文地址:https://www.cnblogs.com/liaods/p/4832673.html