Я использую NSMutableURLRequest для отправки данных POST на серверный PHP script, который отправляет письма с помощью SendGrid. Это прекрасно работает. Однако я не знаю, как правильно упаковать UIImagedata для отправки в виде вложения. Вот мой текущий код:
// Choose an image from your photo library
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
chosenImage = info[UIImagePickerControllerEditedImage]; // chosenImage = UIImage
pickedData = UIImagePNGRepresentation(chosenImage); // pickedData = NSData
attachment = TRUE;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
-(void)sendMail {
toEmailAddress = @"[email protected]";
subject = @"Some Subject";
message = @"Some message...";
fullName = @"Mister Bla Bla";
if (attachment == TRUE) {
// Create NSData object as PNG image data from camera image
NSString *picAttachment = [NSString stringWithFormat:@"%lu",(unsigned long)[pickedData length]];
NSString *picName = @"Photo";
post = [NSString stringWithFormat:@"&toEmailAddress=%@&subject=%@&message=%@&fullName=%@&picAttachment=%@&picName=%@", toEmailAddress, subject, message, fullName, picAttachment, picName];
} else {
post = [NSString stringWithFormat:@"&toEmailAddress=%@&subject=%@&message=%@&fullName=%@", toEmailAddress, subject, message, fullName];
}
NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString * postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSMutableURLRequest * request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.someURL.com/sendgrid.php"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
// send the POST request, and read the reply by creating a new NSURLSession:
NSURLSession *conn = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[conn dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"requestReply: %@", requestReply); // Return response from PHP скрипт on server.
}] resume];
}
Если вы исследуете этот вопрос, вы можете обнаружить, что существует существующая iOS SendGrid lib. К сожалению, это не ответ. Люди в SendGrid говорят мне, чтобы я не использовал lib из-за проблемы безопасности.