gpt4 book ai didi

iphone - 解析一个 NSURL mailto

转载 作者:可可西里 更新时间:2023-11-01 03:28:37 25 4
gpt4 key购买 nike

如何解析 mailto 请求?

'mailto:someone@example.com?cc=someone_else@example.com&subject=This%20is%20the%20subject&body=This%20is%20the%20body'

从这个 NSURL 中,我想提取收件人、主题和正文。我该怎么办?

谢谢

最佳答案

下面是一些代码,可以解析任何 URL 并返回一个字典,其中包含参数和字典中的关联对象。它也适用于 mailto URL。
请注意:此代码假定您使用的是 ARC!

@interface NSString (URLDecoding)  

- (NSString *) URLDecodedString;

@end

@implementation NSString (URLDecoding)

- (NSString *) URLDecodedString {
NSString *result = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (__bridge CFStringRef)self, CFSTR(""), kCFStringEncodingUTF8);
return result;
}

@end

- (NSDictionary *) parameterDictionaryFromURL:(NSURL *)url {
NSMutableDictionary *parameterDictionary = [[NSMutableDictionary alloc] init];
if ([[url scheme] isEqualToString:@"mailto"]) {
NSString *mailtoParameterString = [[url absoluteString] substringFromIndex:[@"mailto:" length]];
NSUInteger questionMarkLocation = [mailtoParameterString rangeOfString:@"?"].location;
[parameterDictionary setObject:[mailtoParameterString substringToIndex:questionMarkLocation] forKey:@"recipient"];

if (questionMarkLocation != NSNotFound) {
NSString *parameterString = [mailtoParameterString substringFromIndex:questionMarkLocation + 1];
NSArray *keyValuePairs = [parameterString componentsSeparatedByString:@"&"];
for (NSString *queryString in keyValuePairs) {
NSArray *keyValuePair = [queryString componentsSeparatedByString:@"="];
if (keyValuePair.count == 2)
[parameterDictionary setObject:[[keyValuePair objectAtIndex:1] URLDecodedString] forKey:[[keyValuePair objectAtIndex:0] URLDecodedString]];
}
}
}
else {
NSString *parameterString = [url parameterString];
NSArray *keyValuePairs = [parameterString componentsSeparatedByString:@"&"];
for (NSString *queryString in keyValuePairs) {
NSArray *keyValuePair = [queryString componentsSeparatedByString:@"="];
if (keyValuePair.count == 2)
[parameterDictionary setObject:[[keyValuePair objectAtIndex:1] URLDecodedString] forKey:[[keyValuePair objectAtIndex:0] URLDecodedString]];
}
}

return [parameterDictionary copy];
}

下面是你如何使用它:

NSURL *mailtoURL = [NSURL URLWithString:@"mailto:foo@example.com?cc=bar@example.com&subject=Greetings%20from%20Cupertino!&body=Wish%20you%20were%20here!"];
NSDictionary *parameterDictionary = [self parameterDictionaryFromURL:mailtoURL];

NSString *recipient = [parameterDictionary objectForKey:@"recipient"];
NSString *subject = [parameterDictionary objectForKey:@"subject"];
NSString *body = [parameterDictionary objectForKey:@"body"];

编辑:
我更新了代码以使用任何 URL,收件人现在在 mailto URL 的字典中。

关于iphone - 解析一个 NSURL mailto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7310396/

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