2011-05-30 83 views
0

我正在使用openURL打開郵件客戶端時遇到問題。這是代碼。使用openURL發送郵件的問題

NSString *subject = @"Demo Subject"; 
NSString *body = @"<html><head>Header</head><body><a href=\"http://example.com\">Here is the demo link</a></body></html>"; 
NSString *urlString = [NSString stringWithFormat:@"mailto:?&subject=%@&body=%@",subject,body]; 
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]]; 

我想,沒有任何一種使用特殊字符需要進行編碼,這是目前做的,而不是在示例文本顯示在這裏。

感謝

回答

5
NSString *htmlBody = @"you probably want something HTML-y here"; 

// First escape the body using a CF call 
NSString *escapedBody = [(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)htmlBody, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8) autorelease]; 

// Then escape the prefix using the NSString method 
NSString *mailtoPrefix = [@"mailto:?subject=Some Subject&body=" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

// Finally, combine to create the fully escaped URL string 
NSString *mailtoStr = [mailtoPrefix stringByAppendingString:escapedBody]; 

// And let the application open the merged URL 
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailtoStr]]; 
+0

Chetu,thanx,它的工作......在這裏,我只是嘗試了openURL的整個urlString的NSUTF8StringEncoding。如果使用CFURLCreateStringByAddingPercentEscapes,它會起什麼作用嗎? – illuminatus 2011-05-30 06:46:20

0
NSString *subject = @"Demo Subject"; 
NSString *body = @"<html><head>Header</head><body><a href=\"http://example.com\">Here is the demo link</a></body></html>"; 
NSString *urlString = [NSString stringWithFormat:@"mailto:?subject=%@&body=%@",subject,body]; 
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]]; 

我在這一行檢查,並比較其更改...

NSString *urlString = [NSString stringWithFormat:@"mailto:?subject=%@&body=%@",subject,body]; 
+1

你做了哪些改變? – 2011-05-30 06:25:10

1

我認爲你可以使用這個

MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init]; 
    [[mail navigationBar] setTintColor:[UIColor blackColor]]; 
    mail.mailComposeDelegate = self; 
    if([MFMailComposeViewController canSendMail]) 
    { 
     [mail setSubject:@"Demo Subject"]; 
     [mail setToRecipients:[NSArray arrayWithObject:@"me"]]; 
     [mail setMessageBody:@"<html><head>Header</head><body><a href=\"http://example.com\">Here is the demo link</a></body></html>" isHTML:YES]; 
     [self presentModalViewController:mail animated:YES]; 
    } 
    [mail release]; 

代替的OpenURL

+0

thanx的迴應,我用這種方式,但因爲我們必須明確地解僱郵件作曲家,我只是嘗試一種替代方式。 – illuminatus 2011-05-30 06:22:18

0

我想你ca n爲此使用MFMailComposeViewController。這可以幫助您使用此方法

- (void)setMessageBody:(NSString*)body isHTML:(BOOL)isHTML 

支持特殊字符即

[yourMailPicker setMessageBody:body isHTML:YES]; 
0

想你的代碼,並得到了該問題[NSURL URLWithString:urlString]這條線返回零。

+0

是的,它就是我的問題,正如@Love Chetu所說的,只需按照步驟對其進行編碼即可。我更喜歡使用CFURLCreateStringByAddingPercentEscapes作爲主體和主體,然後設置urlString。 – illuminatus 2011-06-01 04:33:45