美文网首页
iOS常用转换

iOS常用转换

作者: 在路上浅谈管理 | 来源:发表于2018-10-17 14:52 被阅读0次

    //图片转字符串

    -(NSString *)UIImageToBase64Str:(UIImage *) image

    {

    NSData *data = UIImageJPEGRepresentation(image, 1.0f);

    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    return encodedImageStr;

    }

    //字符串转图片

    -(UIImage *)Base64StrToUIImage:(NSString *)_encodedImageStr

    {

    NSData *_decodedImageData  = [[NSData alloc] initWithBase64Encoding:_encodedImageStr];

    UIImage *_decodedImage      = [UIImage imageWithData:_decodedImageData];

    return _decodedImage;

    }

    //判断软件版本

    +(NSString*)appVersion{

        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];

        CFShow((__bridgeCFTypeRef)(infoDictionary));

        return [infoDictionary objectForKey:@"CFBundleShortVersionString"];

    }

    //是否纯数字

    +(BOOL)isPureNumandCharacters:(NSString*)string

    {

        string = [stringstringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];

        if(string.length>0)

        {

            returnNO;

        }

        return YES;

    }

    //jsonstring ---> nsdictionary

    +(NSDictionary*)dictionaryWithJsonString:(NSString*)jsonstr

    {

        if(jsonstr ==nil) {

            returnnil;

        }

        NSData *jsonData = [jsonstr dataUsingEncoding:NSUTF8StringEncoding];

        NSError*err;

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData

                                                            options:NSJSONReadingMutableContainers

                                                              error:&err];

        if(err) {

            DLog(@"json解析失败:%@",err);

            returnnil;

        }

        returndic;

    }

    //nsdictionary ---> nsstring

    +(NSString*)convertToJsonData:(NSDictionary*)dict

    {

        NSError*error;

        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];

        NSString*jsonString;

        if(!jsonData) {

            DLog(@"error = %@",error);

        }else{

            jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

        }

        NSMutableString *mutStr =[NSMutableString stringWithString:jsonString];

        NSRangerange = {0,jsonString.length};

        //去掉字符串空格

        [mutStrreplaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];

        NSRangerange2 = {0,mutStr.length};

        //去掉换行

        [mutStrreplaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];

        returnmutStr;

    }

    //当前字符串转为颜色值

    + (UIColor*)getColor:(NSString*)hexColor

    {

        unsignedintred,green,blue;

        NSRangerange;

        range.length=2;

        range.location=0;

        [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];

        range.location=2;

        [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];

        range.location=4;

        [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];

        return[UIColorcolorWithRed:(float)(red/255.0f)green:(float)(green /255.0f)blue:(float)(blue /255.0f)alpha:1.0f];

    }

    //比较两个时间的大小

    +(NSInteger)compareDataTimeWith:(NSString*)oneTime anotherTime:(NSString*)anotherTime

    {

        //NSInteger aa;

        NSDateFormatter *dateformater = [[NSDateFormatter alloc] init];

        [dateformatersetDateFormat:@"yyyy-MM-dd HH:mm:ss"];

        NSDate *dta = [[NSDate alloc] init];

        NSDate *dtb = [[NSDate alloc] init];

        dta = [dateformaterdateFromString:oneTime];

        dtb = [dateformaterdateFromString:anotherTime];

        NSTimeInterval secs = [dtb timeIntervalSinceDate:dta];

        if(secs ==0)

            return0;  //两个时间相等

        elseif(secs >0)

            return1;  //后面时间大

        else

            return-1;  //前面时间大

    }

    //秒转换为时分

    + (NSString*)timeFormatted:(int)totalSeconds

    {

        intseconds = totalSeconds %60;

        intminutes = (totalSeconds /60) %60;

        inthours = totalSeconds /3600;

        if(totalSeconds>=3600) {

            return[NSStringstringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];

        }else

            return[NSStringstringWithFormat:@"%02d:%02d",minutes,seconds];

    }

    //获取Wi-Fi的ip地址

    +(NSString*)GetWiFiIPAddressAA

    {

        BOOLsuccess;

        structifaddrs* addrs;

        conststructifaddrs* temp_addr;

        NSString*address =@"";

        success = (getifaddrs(&addrs)==0);

        if(!success){

            DLog(@"fail = has error......");

            returnnil;

        }

        temp_addr=addrs;

        while(temp_addr !=NULL) {

            // Check if interface is en0 which is the wifi connection on the iPhone

            if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"] || [[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"pdp_ip0"])

            {

                //如果是IPV4地址,直接转化

                if(temp_addr->ifa_addr->sa_family==AF_INET){// Get NSString from C String

                    address = [selfformatIPV4Address:((structsockaddr_in*)temp_addr->ifa_addr)->sin_addr];

                }elseif(temp_addr->ifa_addr->sa_family==AF_INET6){//如果是IPV6地址

                    address = [selfformatIPV6Address:((structsockaddr_in6*)temp_addr->ifa_addr)->sin6_addr];

                    if(address && ![addressisEqualToString:@""] && ![address.uppercaseStringhasPrefix:@"FE80"])break;

                }

            }

            temp_addr = temp_addr->ifa_next;

        }

        returnaddress;

    }

    //单个文件的大小

    + (NSString*)fileSizeAtPath:(NSString*) filePath

    {

        NSFileManager* managerFile = [NSFileManager defaultManager];

        if([managerFilefileExistsAtPath:filePath]){

            CGFloatoSize =[[managerFileattributesOfItemAtPath:filePatherror:nil]fileSize]/1024.0;

            if(oSize<1024.0) {

                return [NSString stringWithFormat:@"%.2f KB",oSize];

            }elseif(oSize<(1024.0*1024.0)) {

                return[NSStringstringWithFormat:@"%.2f M",oSize/1024];

            }else{

                return[NSStringstringWithFormat:@"%.2f G",oSize/(1024*1024)];

            }

        }

        return @"0";

    }

    //颜色值转为数组

    +(NSArray*)getRGBWithColor:(UIColor*)color

    {

        CGFloatred  =0.0;

        CGFloatgreen =0.0;

        CGFloatblue  =0.0;

        CGFloatalpha =0.0;

        [colorgetRed:&redgreen:&greenblue:&bluealpha:&alpha];

        return@[@(red *255.0),@(green *255.0),@(blue *255.0),@(alpha)];

    }

    //检测软件通知开关是否打开

    +(BOOL)isUserNotificationEnable

    {

        BOOLisEnable=NO;

        if([[UIDevice currentDevice].systemVersion floatValue]>=8.0f)

        {

            UIUserNotificationSettings *setting=[[UIApplication sharedApplication]currentUserNotificationSettings];

            isEnable=(UIUserNotificationTypeNone==setting.types) ?NO:YES;

        }

        else

        {

            UIRemoteNotificationType type=[[UIApplication sharedApplication]enabledRemoteNotificationTypes];

            isEnable=(UIRemoteNotificationTypeNone== type) ?NO:YES;

        }

        returnisEnable;

    }

    //获取一周的时间日期

    +(NSMutableArray*)getOneWeekDate

    {

        NSMutableArray *weekArray=[NSMutableArray array];

        NSDate *today=[NSDate date];

        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];

        [dateformattersetDateFormat:DATE_MD];

        NSCalendar  * cal=[NSCalendar  currentCalendar];

        NSUInteger  unitFlags=NSCalendarUnitDay | NSCalendarUnitMonth;

        NSString*todayDay=NSLocalizedString(@"Today",nil);

        NSTimeIntervalnoeday=24*60*60*1;

        for(intdis=6; dis>0; dis--) {

            NSDate*theDate = [todayinitWithTimeIntervalSinceNow: -noeday*dis];

            NSDateComponents* conponent= [calcomponents:unitFlagsfromDate:theDate];

            NSIntegermonth=[conponentmonth];

            NSIntegerday=[conponentday];

            NSString*weakday=[NSStringstringWithFormat:@"%2ld/%2ld",(long)day,(long)month];

            [weekArrayaddObject:weakday];

        }

        [weekArrayaddObject:todayDay];

        returnweekArray;

    }

    //utf8编码

    +(NSString*)encoding_utf8StringWithstr:(NSString*)str

    {

        return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)str,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8 ));

    }

    //utf8解码

    +(NSString*)decoding_utf8stringwithencStr:(NSString*)encStr

    {

        return [encStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    }

    相关文章

      网友评论

          本文标题:iOS常用转换

          本文链接:https://www.haomeiwen.com/subject/avfrzftx.html