iOS封装常用的方法

//根据日期算出周几

+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate

{

    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];

    [calendar setTimeZone: timeZone];

    NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;

    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];


return [weekdays objectAtIndex:theComponents.weekday];

}


//转化为时间字符串

+ (NSString *)dateStringFromNumberTimer:(NSString *)timerStr {

    //转化为Double

    double t = [timerStr doubleValue];

    //计算出距离1970NSDate

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:t];

    //转化为时间格式化字符串

    //NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];


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

    df.dateFormat = @"yyyy-MM-dd HH:mm:ss";

    //转化为时间字符串

    return [df stringFromDate:date];

}

//动态计算行高

//根据字符串的实际内容的多少在固定的宽度和字体的大小,动态的计算出实际的高度

+ (CGFloat)textHeightFromTextString:(NSString *)text width:(CGFloat)textWidth fontSize:(CGFloat)size{

    if ([MZLUtility getCurrentIOS] >= 7.0) {

        //iOS7之后

        /*

        第一个参数: 预设空间宽度固定  高度预设一个最大值

        第二个参数: 行间距如果超出范围是否截断

        第三个参数: 属性字典可以设置字体大小

         */

        NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:size]};

        CGRect rect = [text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];

        //返回计算出的行高

        return rect.size.height;


    }else {

        //iOS7之前

        /*

         1.第一个参数 设置的字体固定大小

         2.预设宽度和高度 宽度是固定的高度一般写成最大值

         3.换行模式字符换行

         */

        CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:size] constrainedToSize:CGSizeMake(textWidth, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];

        return textSize.height;//返回计算出得行高

    }

}

//获取iOS版本号

+ (double)getCurrentIOS {

    return [[[UIDevice currentDevice] systemVersion] doubleValue];

}

+ (CGSize)getScreenSize {

    return [[UIScreen mainScreen] bounds].size;

}

//获得当前系统时间到指定时间的时间差字符串,传入目标时间字符串和格式

+(NSString*)stringNowToDate:(NSString*)toDate formater:(NSString*)formatStr

{


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

if (formatStr) {

    [formater setDateFormat:formatStr];

}

else{

    [formater setDateFormat:[NSString stringWithFormat:@"yyyy-MM-dd HH:mm:ss"]];

}

NSDate *date=[formater dateFromString:toDate];


return [self stringNowToDate:date];


}

//获得到指定时间的时间差字符串,格式在此方法内返回前自己根据需要格式化

+(NSString*)stringNowToDate:(NSDate*)toDate

{

    //创建日期 NSCalendar对象

    NSCalendar *cal = [NSCalendar currentCalendar];

    //得到当前时间

    NSDate *today = [NSDate date];


//用来得到具体的时差,位运算

unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ;


if (toDate && today) {//不为nil进行转化

    NSDateComponents *d = [cal components:unitFlags fromDate:today toDate:toDate options:0 ];


    //NSString *dateStr=[NSString stringWithFormat:@"%d%d%d%d%d%d",[d year],[d month], [d day], [d hour], [d minute], [d second]];

    NSString *dateStr=[NSString stringWithFormat:@"%02ld:%02ld:%02ld",[d hour], [d minute], [d second]];

    return dateStr;

}

return @"";

}

//MD5加密字符串

NSString * MD5Hash(NSString *aString) {

    const char *cStr = [aString 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]];

}

//获取一个文件 在沙盒Library/Caches/ 目录下的路径

+ (NSString *)getFullPathWithFile:(NSString *)urlName {


//先获取沙盒中的Library/Caches/路径

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

NSString *myCacheDirectory = [docPath stringByAppendingPathComponent:@"MyCaches"];

//检测MyCaches文件夹是否存在

if (![[NSFileManager defaultManager] fileExistsAtPath:myCacheDirectory]) {

    //不存在那么创建

    [[NSFileManager defaultManager] createDirectoryAtPath:myCacheDirectory withIntermediateDirectories:YES attributes:nil error:nil];

}

//md5进行加密 转化为一串十六进制数字 (md5加密可以把一个字符串转化为一串唯一的用十六进制表示的串)

NSString * newName = MD5Hash(urlName);


//拼接路径

return [myCacheDirectory stringByAppendingPathComponent:newName];

}

//检测缓存文件 是否超时

+ (BOOL)isTimeOutWithFile:(NSString *)filePath timeOut:(double)timeOut {

    //获取文件的属性

    NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];

    //获取文件的上次的修改时间

    NSDate *lastModfyDate = fileDict.fileModificationDate;

    //算出时间差获取当前系统时间 lastModfyDate时间差

    NSTimeInterval sub = [[NSDate date] timeIntervalSinceDate:lastModfyDate];

    if (sub < 0) {

        sub = -sub;

    }

    //比较是否超时

    if (sub > timeOut) {

        //如果时间差大于 设置的超时时间那么就表示超时

        return YES;

    }

    return NO;

}

//清除缓存

+ (void) resetCache {

    [[NSFileManager defaultManager] removeItemAtPath:[MZLCache cacheDirectory] error:nil];

}

//缓存目录

+ (NSString*) cacheDirectory {

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

    NSString *cacheDirectory = [paths objectAtIndex:0];

    cacheDirectory = [cacheDirectory stringByAppendingPathComponent:@"MZLCaches"];

    return cacheDirectory;

}

//删除指定的缓存

+ (NSData*) objectForKey:(NSString*)key {

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];


    if ([fileManager fileExistsAtPath:filename])

    {

        NSDate *modificationDate = [[fileManager attributesOfItemAtPath:filename error:nil] objectForKey:NSFileModificationDate];

        if ([modificationDate timeIntervalSinceNow] > cacheTime) {

            [fileManager removeItemAtPath:filename error:nil];

        } else {

            NSData *data = [NSData dataWithContentsOfFile:filename];

            return data;

        }

    }

    return nil;

}

//创建指定缓存

+ (void) setObject:(NSData*)data forKey:(NSString*)key {

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];


    BOOL isDir = YES;

    if (![fileManager fileExistsAtPath:self.cacheDirectory isDirectory:&isDir]) {

        [fileManager createDirectoryAtPath:self.cacheDirectory withIntermediateDirectories:NO attributes:nil error:nil];

    }


    NSError *error;

    @try {

        [data writeToFile:filename options:NSDataWritingAtomic error:&error];

    }

    @catch (NSException * e) {

        //TODO: error handling maybe

    }

}

//获取某个路径下文件大小

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


    NSFileManager* manager = [NSFileManager defaultManager];

    if ([manager fileExistsAtPath:filePath]){


    return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];

}

return 0;


}

//获取缓存大小

+ (float ) folderSizeAtPath:(NSString*) folderPath{

    NSFileManager* manager = [NSFileManager defaultManager];

    if (![manager fileExistsAtPath:folderPath])

        return 0;

    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];

    NSString* fileName;

    long long folderSize = 0;

    while ((fileName = [childFilesEnumerator nextObject]) != nil){

        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];

        folderSize += [MZLCache fileSizeAtPath:fileAbsolutePath];

    }

    return folderSize/(1024.0*1024.0);

}

// 判断字符是否为空

+(BOOL)isNull:(NSString*)str

{

    if(str == nil)

    {

        return YES;

    }

    

    if([str isEqualToString:@""])

    {

        return YES;

    }

    

    return NO;

}

//返回时间

+ (NSString *)compareCurrentTime:(NSString *)dateString

{

    

    //把字符串转为NSdate

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

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

    NSDate *timeDate = [dateFormatter dateFromString:dateString];

    

    //得到与当前时间差

    NSTimeInterval  timeInterval = [timeDate timeIntervalSinceNow];

    timeInterval = -timeInterval;

    //标准时间和北京时间差8个小时

    timeInterval = timeInterval - 8*60*60;

    

    long temp = 0;

    NSString *result;

    if (timeInterval < 60) {

        result = [NSString stringWithFormat:@"刚刚"];

    }

    else if((temp = timeInterval/60) <60){

        result = [NSString stringWithFormat:@"%ld分钟前",temp];

    }

    

    else if((temp = temp/60) <24){

        result = [NSString stringWithFormat:@"%ld小时前",temp];

    }

    

    else if((temp = temp/24) <30){

        result = [NSString stringWithFormat:@"%ld天前",temp];

    }

    

    else if((temp = temp/30) <12){

        result = [NSString stringWithFormat:@"%ld月前",temp];

    }

    else{

        temp = temp/12;

        result = [NSString stringWithFormat:@"%ld年前",temp];

    }

    

    return  result;

}


/** 通过行数, 返回更新时间 */

+ (NSString *)updateTimeForRow:(NSInteger)row {

    // 获取当前时时间戳 1466386762.345715 十位整数 6位小数

    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];

    // 创建歌曲时间戳(后台返回的时间 一般是13位数字)

    //    NSTimeInterval createTime = row/;

    // 时间差

    NSTimeInterval time = currentTime - row;

    

    // 秒转小时

    NSInteger hours = time/3600;

    if (hours<24) {

        return [NSString stringWithFormat:@"%ld小时前",hours];

    }

    //秒转天数

    NSInteger days = time/3600/24;

    if (days < 30) {

        return [NSString stringWithFormat:@"%ld天前",days];

    }

    //秒转月

    NSInteger months = time/3600/24/30;

    if (months < 12) {

        return [NSString stringWithFormat:@"%ld月前",months];

    }

    //秒转年

    NSInteger years = time/3600/24/30/12;

    return [NSString stringWithFormat:@"%ld年前",years];

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Unity 中调用 iOS方法需要使用 Unity 的插件机制,具体步骤如下: 1. 创建一个 C# 脚本,用于调用 iOS方法。例如,创建一个名为 iOSBridge.cs 的脚本。 2. 在脚本中引入以下命名空间: ``` using System.Runtime.InteropServices; using UnityEngine; ``` 3. 声明一个与 iOS 方法对应的 C 函数,以及一个与该函数对应的 C# 函数。例如,我们要调用 iOS 中名为 "sendDataToServer" 的方法,可以这样声明: ``` [DllImport("__Internal")] private static extern void sendDataToServer(string data); public static void SendDataToServer(string data) { sendDataToServer(data); } ``` 4. 在 Unity 中创建一个 iOS 插件。创建一个名为 "iOS" 的文件夹,并在该文件夹下创建一个名为 "iOSBridge.mm" 的文件。 5. 将 "iOSBridge.mm" 中的代码实现为调用 iOS 的 "sendDataToServer" 方法: ``` #import "iOSBridge.h" #import "UnityAppController.h" void sendDataToServer(const char* data) { NSString* nsData = [NSString stringWithUTF8String:data]; UnitySendMessage("GameObjectName", "MethodName", [nsData UTF8String]); } ``` 其中, "GameObjectName" 和 "MethodName" 分别是你在 Unity 中调用的 GameObject 名称和方法名称。 6. 编译 iOS 插件。将 "iOSBridge.mm" 添加到 Xcode 项目中,并编译。 7. 在 Unity 中调用 iOS 方法。在你的 C# 脚本中,调用 "SendDataToServer" 方法即可: ``` iOSBridge.SendDataToServer("Hello, iOS!"); ``` 这样,就可以将 "Hello, iOS!" 传递给 iOS 中的 "sendDataToServer" 方法了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值