1.给NSString建一个分类
.h文件
/**
判断该字符串是不是一个有效的URL
@return YES:是一个有效的URL or NO
*/
- (BOOL)isValidUrl;
/** 根据图片名 判断是否是gif图 */
- (BOOL)isGifImage;
/** 根据图片data 判断是否是gif图 */
+ (BOOL)isGifWithImageData: (NSData *)data;
/**
根据image的data 判断图片类型
@param data 图片data
@return 图片类型(png、jpg...)
*/
+ (NSString *)contentTypeWithImageData: (NSData *)data;
.m文件
- (BOOL)isValidUrl {
NSString *regex =@"[a-zA-z]+://[^\\s]*";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
return [urlTest evaluateWithObject:self];
}
- (BOOL)isGifImage {
NSString *ext = self.pathExtension.lowercaseString;
if ([ext isEqualToString:@"gif"]) {
return YES;
}
return NO;
}
+ (BOOL)isGifWithImageData: (NSData *)data {
if ([[self contentTypeWithImageData:data] isEqualToString:@"gif"]) {
return YES;
}
return NO;
}
+ (NSString *)contentTypeWithImageData: (NSData *)data {
uint8_t c;
[data getBytes:&c length:1];
switch (c) {
case 0xFF:
return @"jpeg";
case 0x89:
return @"png";
case 0x47:
return @"gif";
case 0x49:
case 0x4D:
return @"tiff";
case 0x52:
if ([data length] < 12) {
return nil;
}
NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
return @"webp";
}
return nil;
}
return nil;
}