iOS每日一记之-----------常用小工具代码合集

/**
 *  HTTP GET 请求
 **/
+(NSData *) doHttpGet:(NSString *)url
{
    NSURL *uri = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uri];
    [request setHTTPMethod: @"GET" ];
    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
    return returnData;
}

/**
 *  HTTP POST请求
 **/
+(NSData *) doHttpPost:(NSString *)url withString:(NSString *)param
{
    NSData *data = nil;
    if(param != nil && [param isEqualToString:@""] == NO){
        param = [param stringByAddingPercentEscapesUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];
        data = [param dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];
    }
    //调用withParam NSData*类型的方法.
    return [self doHttpPost:url withParam:data];
}


/**
 *  HTTP POST请求
 **/
+(NSData *) doHttpPost:(NSString *)url withParam:(NSData *)param
{
    //新建请求
    NSURL *uri = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:uri cachePolicy:NSURLRequestReloadIgnoringLocalCacheData  timeoutInterval:40.0];
    //设置请求参数
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    if(param != nil)
        [request setHTTPBody:param];
    //打开访问网络的状态提示
    //[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    //请求链接
    //NSError *error = nil;
    NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    //NSLog(@"%d: %@", error.code, error.description);
    //关闭访问网络的状态提示
    //[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    //返回结果
    return retData;
}


/**
 *  获取网络图片
 **/
+(UIImage *) getImageFromUrl:(NSString *)url
{
    if(url == nil || [url isEqualToString:@""]){
        return nil;
    }
    url = StringByTrimWhiteSpace(url);
    NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:url]];
    UIImage *image =[[UIImage alloc] initWithData:imageData];
    return image;
}

/**
 *  获取网络图片的内容
 **/
+(NSData *)getImageDataFromUrl:(NSString *)url
{
    if(url == nil || [url isEqualToString:@""]){
        return nil;
    }
    
    NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:url]];
    return imageData;
}



#pragma mark - 字符串处理


/**
 *  利用正则表达示获取字符串的匹配结果
 **/
+(NSString *) getRegExpressResult:(NSString *)source regExp:(NSString *)regExp
{
    NSString *temp = [NSString stringWithFormat:@"%@", source];
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regExp options:NSRegularExpressionCaseInsensitive error:nil];
    
    if (regex != nil) {
        NSTextCheckingResult *firstMatch = [regex firstMatchInString:temp options:0 range:NSMakeRange(0, [temp length])];
        
        if (firstMatch) {
            NSRange resultRange = [firstMatch rangeAtIndex:0];
            //截取数据
            NSString *result = [temp substringWithRange:resultRange];
            //返回结果
            return result;
        }
    }
    return @"";
}

/**
 *  匹配字符串中整个HTML标记的内容
 **/
+(NSString *) getHtmlText:(NSString *)source tagName:(NSString *)tag
{
    NSString *regexp = [NSString stringWithFormat:@"<\\s*%@\\s+([^>]*)\\s*>([^/%@>]*</%@>)?", tag, tag, tag];
    return [BaseFunction getRegExpressResult:source regExp:regexp];
}


/**
 *  匹配HTML标记内容中的属性值
 **/
+(NSString *) getHtmlTagAttr:(NSString *)tagContext attrName:(NSString *)attr
{
    NSString *regexp = [NSString stringWithFormat: @"%@\\s*=\\s*?(['\"][^'\"]*?)['\"]", attr];
    NSString *result = [BaseFunction getRegExpressResult:tagContext regExp:regexp];
    //替换
    NSString *oldstr = [NSString stringWithFormat:@"%@=\"", attr];
    NSString *newstr = [result stringByReplacingOccurrencesOfString:oldstr withString:@""];
    newstr = [newstr substringToIndex:[newstr length] - 1];
    return newstr;
}

/**
 *  获取HTML标记的文本
 **/
+(NSString *) getHTmlTagText:(NSString *)tagContext
{
    NSString *regExp = @"<\\s*\\w+\\s+([^>]*)\\s*>";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regExp options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSTextCheckingResult *firstMatch = [regex firstMatchInString:tagContext options:0 range:NSMakeRange(0, [tagContext length])];
    NSRange resultRange = [firstMatch rangeAtIndex:0];
    NSString *newStr = [tagContext substringFromIndex:resultRange.length];
    
    regExp = @"</\\w+\\s*>";
    regex = [NSRegularExpression regularExpressionWithPattern:regExp options:NSRegularExpressionCaseInsensitive error:nil];
    firstMatch = [regex firstMatchInString:newStr options:0 range:NSMakeRange(0, [newStr length])];
    resultRange = [firstMatch rangeAtIndex:0];
    
    return [newStr substringToIndex:resultRange.location];
}

/**
 *  替换HTML标签
 **/
+(NSString *) replaceHtmlTag:(NSString *)source
{
    source = [BaseFunction replaceString:source byRegexp:@"<[^>]+>"];
    return [BaseFunction replaceString:source byRegexp:@"</[^>]+>"];
}

+(NSString *) replaceString:(NSString *)source byRegexp:(NSString *)exp
{
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:exp options:0 error:nil];
    
    if(regex == nil)
        return source;
    
    NSString *ret = [NSString stringWithFormat:@"%@", source];
    NSArray *array = [regex matchesInString:ret options:NSMatchingReportProgress range:NSMakeRange(0, [ret length])];
    for(int i = (int)[array count] - 1; i >= 0; i--)
    {
        NSTextCheckingResult *tcr = [array objectAtIndex:i];
        NSRange range = [tcr range];
        ret = [ret stringByReplacingCharactersInRange:range withString:@""];
    }
    return ret;
}



/**
 *  正则验证
 **/
+(BOOL) string:(NSString *)source MatchRegex:(NSString *) exp
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", exp];
    return [predicate evaluateWithObject:source];
}


/**
 *  获取正则表达式中匹配的个数
 **/
+ (NSInteger) getMatchCount:(NSString *)text inRegx:(NSString *)exp
{
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:exp options:0 error:nil];
    
    int count = 0;
    if (regex != nil) {
        NSArray *array = [regex matchesInString:text options:NSMatchingReportProgress range:NSMakeRange(0, [text length])];
        
        for(int i=0; i< [array count]; i++)
        {
            NSTextCheckingResult *tcr = [array objectAtIndex:i];
            NSRange range = [tcr range];
            count += range.length;
        }
    }
    return count;
}


/**
 *  替换XML敏感字符
 **/
+ (NSString *) replaceXMLSensitiveLettler:(NSString *)text
{
    NSString *tmp = [text stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"];
    tmp = [tmp stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"];
    tmp = [tmp stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];
    return tmp;
}

/**
 *  分离坐标
 **/
+(void) separateCoordinate:(NSString *)coord lat:(NSString **)lat lng:(NSString **)lng
{
    *lng = @"", *lat = @"";
    //验证数据的合法性
    if(coord == nil){ return; }
    coord = StringByTrimWhiteSpace(coord);
    if(IsStringEmpty(coord)){
        return;
    }
    
    //将坐标分开
    NSArray *coordArray = [coord componentsSeparatedByString:@","];
    if([coordArray count]>0)
        *lng = [coordArray objectAtIndex:0];
    if([coordArray count]>1)
        *lat = [coordArray objectAtIndex:1];
}


/**
 *  从文件路径中分解出文件名
 **/
+ (NSString *) splitFileNameForPath:(NSString *)filePath
{
    NSArray *array = [filePath componentsSeparatedByString:@"/"];
    return [array lastObject];
}


/**
 *  从文件路径中分解出文件的扩展名
 **/
+ (NSString *) getFileExtension:(NSString *)filePath
{
    NSString *fileName = [self splitFileNameForPath:filePath];
    NSArray *array = [fileName componentsSeparatedByString:@"."];
    return [NSString stringWithFormat:@".%@",[array lastObject]];
}

/**
 *  获取设备型号
 **/
+ (NSString *) platform
{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = (char *)malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    NSRange range = [platform rangeOfString:@","];
    return [platform substringToIndex:range.location];
}


/**
 *  MD5加密
 **/
+ (NSString *)md5Digest:(NSString *)str {
    const char *cStr = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    NSMutableString *md5Result = [[NSMutableString alloc] init];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [md5Result appendFormat:@"%02x", result[i]];
    }
    
    return md5Result;
//    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]];
}

+ (NSString *)SHA1:(NSString *)str {
    const char *cStr = [str UTF8String];
    NSData *data = [NSData dataWithBytes:cStr length:str.length];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, (CC_LONG)data.length, digest);
    NSMutableString *result = [[NSMutableString alloc] init];
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02x", digest[i]];
    }
    
    return result;
}


//判断是否为整形
+ (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

//判断是否为浮点形
+ (BOOL)isPureFloat:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return [scan scanFloat:&val] && [scan isAtEnd];
}

/**
 *  版本比较
 **/
+ (BOOL)isVersion:(NSString*)versionA biggerThanVersion:(NSString*)versionB
{
    NSArray *arrayNow = [versionB componentsSeparatedByString:@"."];
    NSArray *arrayNew = [versionA componentsSeparatedByString:@"."];
    BOOL isBigger = NO;
    NSInteger i = arrayNew.count > arrayNow.count? arrayNow.count : arrayNew.count;
    NSInteger j = 0;
    BOOL hasResult = NO;
    for (j = 0; j < i; j ++) {
        NSString* strNew = [arrayNew objectAtIndex:j];
        NSString* strNow = [arrayNow objectAtIndex:j];
        if ([strNew integerValue] > [strNow integerValue]) {
            hasResult = YES;
            isBigger = YES;
            break;
        }
        if ([strNew integerValue] < [strNow integerValue]) {
            hasResult = YES;
            isBigger = NO;
            break;
        }
    }
    if (!hasResult) {
        if (arrayNew.count > arrayNow.count) {
            NSInteger nTmp = 0;
            NSInteger k = 0;
            for (k = arrayNow.count; k < arrayNew.count; k++) {
                nTmp += [[arrayNew objectAtIndex:k]integerValue];
            }
            if (nTmp > 0) {
                isBigger = YES;
            }
        }
    }
    return isBigger;
}



你可能感兴趣的:(ios)