gpt4 book ai didi

objective-c - Objective-C 中的 Mime 编码字解析

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:05:48 24 4
gpt4 key购买 nike

OS X 或 iOS 是否提供 API 来解析 MIME Encoded-Word ?这些可爱的字符串:

=?iso-8859-1?Q?=A1Hola,_se=F1or!?=

或者,是否有已知的开源库可以执行此操作?

最佳答案

我拿走了@NickolayO. 的answer , 添加 base-64 支持 QSStrings并使用 componentsSeparatedByString:stringByReplacingOccurrencesOfString:withString: 缩短了代码。

我已经在 GitHub 上提供了代码.为方便起见,这里有一个片段:

@implementation NSString (MimeEncodedWord)

- (BOOL) isMimeEncodedWord
{
return [self hasPrefix:@"=?"] && [self hasSuffix:@"?="];
}

+ (NSString*) stringWithMimeEncodedWord:(NSString*)word
{ // Example: =?iso-8859-1?Q?=A1Hola,_se=F1or!?=
NSArray *components = [word componentsSeparatedByString:@"?"];
if (components.count < 5) return nil;

NSString *charset = [components objectAtIndex:1];
NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)charset)); // TODO: What happens if the encoding is invalid?

NSString *encodingType = [components objectAtIndex:2];
NSString *encodedText = [components objectAtIndex:3];
if ([encodingType isEqualToString:@"Q"])
{ // quoted-printable
encodedText = [encodedText stringByReplacingOccurrencesOfString:@"_" withString:@" "];
encodedText = [encodedText stringByReplacingOccurrencesOfString:@"=" withString:@"%"];
NSString *decoded = [encodedText stringByReplacingPercentEscapesUsingEncoding:encoding];
return decoded;
} else if ([encodingType isEqualToString:@"B"])
{ // base64
NSData *data = [QSStrings decodeBase64WithString:encodedText];
NSString *decoded = [[NSString alloc] initWithData:data encoding:encoding];
return decoded;
} else {
NSLog(@"%@ is not a valid encoding (must be Q or B)", encodingType);
return nil;
}
}

@end

关于objective-c - Objective-C 中的 Mime 编码字解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14014738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com