0

我在发送电子邮件时遇到问题。如果消息只有一个词,代码就可以正常工作。当我添加多个单词时,即带有空格或符号,它会出错并显示“出现连接错误。请确保您有互联网连接,然后再试一次”。

- (void)sendAction {

NSString *email = [self.emailTxt text];
NSString *message = [self.messageTxt text];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?email=%@&message=%@", kITSuggestionPage, email, message]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    NSString *title = (!error)? @"Message Sent" : @"Error";
    NSString *message = (!error)? @"Thank you for your Feedback, we hope it will help us to make this product even better." : @"There was an connection error. Please make sure you have internet connection and try again later.";
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
    [alert show];

    NSLog(@"Error: %@", error.localizedDescription);
}];


if (email && (email.length > 0)) {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:email forKey:kITUserEmailKey];
    [userDefaults synchronize];
}
}
4

2 回答 2

2

您必须对参数进行URL 转义message(本质上是用百分比编码替换 URL 中不允许的某些字符,例如%20空格)。

示例(假设您使用的是 ARC):

NSString *message = [self.messageTxt text];
message = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)message, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8));
NSURL *url = ...
于 2013-04-27T11:36:50.000 回答
0

尝试添加 %20 代替消息的空格。如果它现在工作正常,那么问题出在编码上。在发送请求之前对您的 URL 进行编码。

NSString *urlString = [urlString stringByReplacingPercentEscapesUsingEncoding :NSASCIIStringEncoding];

这将对 URL 进行编码。

于 2013-04-27T09:33:07.470 回答