常用的OC函数工具

一、判断NSString中的字符是否为中文

在Unicode编码的NSString中,如何遍历字符串中的汉字呢?网上查了很多方法,几乎都是这一种:

unichar ch = [string characterAtIndex:i];  
if (0x4e00 < ch  && ch < 0x9fff)  
{  
    //含有中文 
}  

这样的确可以判断大多数中文符号,但是少数字符比如句号“。”在unichar存储的16进制值要小于0x4e00,查了很多资料试了很多例子发现只有这样判断才是正确的:

unichar ch = [string characterAtIndex:i];  
if ((int)(ch)>127)  
{  
    //含有中文 
}
else if((ch >64)&&(ch <91)){
    NSLog(@"字符串中含有大写英文字母");
}else if((ch >96)&&( ch<123)){
    NSLog(@"字符串中含有小写英文字母");
}else if((ch>47)&&(ch<58)){
    NSLog(@"字符串中含有数字");
}else{
    NSLog(@"字符串中含有非法字符");
}

二、获取软件包名Bundle Identifier

///软件包名Bundle Identifier
-(NSString*)getBundleIdentifier
{
    return [[NSBundle mainBundle] bundleIdentifier];
}

三、ios系统版本

-(NSString*)getIOSVersion
{
    return [[UIDevice currentDevice] systemVersion];
}

四、APP软件版本

-(NSString*)getAppVersion
{
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)@"CFBundleShortVersionString"];
    return version;
}

五、APP软件build版本

-(NSString*)getAppBuildVersion
{
    NSString *buildVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)@"CFBundleVersion"];
    return buildVersion;
}

六、将字典或者数组转化为Json Data数据

- (NSData *)toJSONData:(id)theData{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData options:NSJSONWritingPrettyPrinted error:&error];
    if ([jsonData length] > 0 && error == nil){
        return jsonData;
    }else{
        return nil;
    }
}

七、将Json Data转化为字典或者数组

// 将JSONDATA转化为字典或者数组
- (id)DataToArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}

八、将字典或者数组转化为json字符串数据

- (NSString *)toJSONStr:(id)theData
{
    NSData *jsonData = [self toJSONData:theData];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

九、将JSON串转化为字典或者数组

- (id)StrToArrayOrNSDictionary:(NSString *)jsonStr
{
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    return [self DataToArrayOrNSDictionary:jsonData];
}

十、NSArray转为NSString

-(NSString*)ArrayToString:(NSArray*)array
{
    return [array componentsJoinedByString:@","];
}

十一、NSString转为NSArray

-(NSArray*)StringToArray:(NSString*)str
{
    return [str componentsSeparatedByString:@","];
}

十二、unicode转换为中文

-(NSString*)convertUnicodeString:(NSString*)unicodeStr
{
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                           mutabilityOption:NSPropertyListImmutable
                                                                     format:NULL
                                                           errorDescription:NULL];
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}

十三、从文件获取json内容

-(id)getJsonDataFromFileName:(NSString*)jsonName
{
    NSString *jsonPath = [[NSBundle mainBundle] pathForResource:jsonName ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:jsonPath];
    id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    return result;
}

十四、将UIImage内容写入本地保存,返回保存过的路径

-(NSString*)savedImagePathWithUIImage:(UIImage*)img WithFileName:(NSString*)fileName
{
    //压缩
//    NSData *imagedata = UIImagePNGRepresentation(img);
    NSData *imagedata = UIImageJPEGRepresentation(img, 0.7);
    NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];
    NSString *savedImagePath=[documentsDirectory stringByAppendingPathComponent:fileName];
    [imagedata writeToFile:savedImagePath atomically:YES];
    return savedImagePath;
}

十五、将Data内容写入本地保存,重新命名,返回保存过的路径

-(NSString*)savedPathWithData:(NSData*)data WithFileName:(NSString*)fileName
{
    NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];
    NSString *savedImagePath=[documentsDirectory stringByAppendingPathComponent:fileName];
    [data writeToFile:savedImagePath atomically:YES];
    return savedImagePath;
}

十六、MD5加密

-(NSString*)getMD5withStr:(NSString*)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
    return [[NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ] lowercaseString];
}

十七、获取时间戳

-(NSString*)getTimeStamp
{
    return [NSString stringWithFormat:@"%.0f",[[NSDate date] timeIntervalSince1970]];
}

十八、获取视频指定第几秒的截图

-(UIImage*)getVideoPreViewImageFromVideoPath:(NSString*)videoPath withAtTime:(float)atTime
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:videoPath] options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    gen.requestedTimeToleranceAfter = kCMTimeZero;
    gen.requestedTimeToleranceBefore = kCMTimeZero;
    CMTime time = CMTimeMakeWithSeconds(atTime, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *img = [[UIImage alloc] initWithCGImage:image];
    UIGraphicsBeginImageContext(CGSizeMake(JLXScreenSize.width, JLXScreenSize.height));
    [img drawInRect:CGRectMake(0, 0, JLXScreenSize.width, JLXScreenSize.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRelease(image);
    return scaledImage;
}

十九、获取本地视频的时长

-(NSUInteger)durationWithVideo:(NSString *)videoPath
{
    NSDictionary *opts = [NSDictionary dictionaryWithObject:@(NO) forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:videoPath] options:opts];     //初始化视频媒体文件
    NSUInteger second = 0;
    second = urlAsset.duration.value / urlAsset.duration.timescale; // 获取视频总时长,单位秒

    return second;
}

二十、是否是平板

-(BOOL)isPad
{
    return [[UIDevice currentDevice].model isEqualToString:@"iPad"];
}

二十一、是否有麦克风权限

typedef enum : NSUInteger {
    JLXAuthorized = 1,  //用户允许
    JLXDenied,          //用户拒绝
    JLXNotDetermined,   //用户尚未选择
} JLXPrivate;
-(JLXPrivate)hasAVMediaTypeAudio
{
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (status == AVAuthorizationStatusAuthorized){
        return JLXAuthorized;
    }
    else if (status == AVAuthorizationStatusNotDetermined){
        return JLXNotDetermined;
    }
    else{
        return JLXDenied;
    }
}

二十二、是否有拍照权限

-(JLXPrivate)hasAVMediaTypeVideo
{
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusAuthorized){
        return JLXAuthorized;
    }
    else if (status == AVAuthorizationStatusNotDetermined){
        return JLXNotDetermined;
    }
    else{
        return JLXDenied;
    }
}

二十三、是否有相册权限

-(JLXPrivate)hasPhotoLibrary
{
    PHAuthorizationStatus status=[PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusAuthorized){
        return JLXAuthorized;
    }
    else if (status == PHAuthorizationStatusNotDetermined){
        return JLXNotDetermined;
    }
    else{
        return JLXDenied;
    }
    
}

二十四、申请麦克风权限

-(void)getAVMediaTypeAudio
{
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        
    }];
}

二十五、申请拍照权限

-(void)getAVMediaTypeVideo
{
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
       
    }];
}

二十六、申请相册权限

-(void)getPhotoLibrary
{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
    }];
}

二十七、打开系统设置

-(void)openSetting
{
    NSURL *settingUrl = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:settingUrl]) {
        [[UIApplication sharedApplication] openURL:settingUrl];
    }
}

参考文章:

Last modification:May 5th, 2017 at 09:59 am
如果看了这个文章可以让你少加会班,可以请我喝杯可乐
已打赏名单
微信公众号

Leave a Comment