У меня есть функция отправки сообщений в моем приложении, и я реализовал ее с помощью MFMessageComposeViewController. Я могу прикрепить фотографии к сообщению в iOS9, но не в iOS 10? Есть ли у кого-нибудь такая же проблема?
Отправка фото с помощью MFMessageComposeViewController отключена в ios10
Ответы (3)
Версия Swift 5.0: вызовите приведенный ниже метод с именем displayMessageInterface
:
– Важное примечание:
composeViewController.addAttachmentData(dataImage!, typeIdentifier: "image/png", filename: "ImageData.png")
В приведенной выше строке имя файла должно иметь тип
abc.png
в моем случае илиabc.jpeg
, если вы используете данные изображения jpeg, а typeIdentifier должен следовать заimage/png
иimage/jpeg
соответственно. Мне пришлось много потрудиться, чтобы это выяснить. Причина, по которой я пишу этот ответ, даже когда других ответов уже достаточно.
Для получения дополнительной информации об идентификаторах типов используйте эту ссылку: https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html#//apple_ref/doc/uid/TP40009259-SW1
fileprivate func displayMessageInterface() {
if MFMessageComposeViewController.canSendText() {
let composeViewController = MFMessageComposeViewController()
composeViewController.messageComposeDelegate = self
composeViewController.body = "Enter your text body here."
if MFMessageComposeViewController.canSendAttachments() {
let image = UIImage(named: "image-name")!
let dataImage = image.pngData()
guard dataImage != nil else {
return
}
composeViewController.addAttachmentData(dataImage!, typeIdentifier: "image/png", filename: "ImageData.png")
}
self.present(composeViewController, animated: true)
} else {
print("Can't send messages.")
}
}
Поскольку я упомянул делегата в приведенном выше методе, вы можете использовать его таким образом в случае UIViewController
:
extension UIViewController: MFMessageComposeViewControllerDelegate {
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
if result == .failed {
print("could not send message")
}
self.dismiss(animated: true)
}
}
Пожалуйста, найдите приведенный ниже код в виде прикрепленного изображения, и я успешно запустил iOS 10
.
- (void)sendImgAttachment {
if([MFMessageComposeViewController canSendText]) {
MFMessageComposeViewController *messageController = [[MFMessageComposeViewController alloc] init]; // Create message VC
messageController.messageComposeDelegate = self; // Set delegate to current instance
NSMutableArray *recipients = [[NSMutableArray alloc] init]; // Create an array to hold the recipients
[recipients addObject:@"555-555-5555"]; // Append example phone number to array
messageController.recipients = recipients; // Set the recipients of the message to the created array
messageController.body = @"Example message"; // Set initial text to example message
NSData *dataImg = UIImagePNGRepresentation([UIImage imageNamed:@"logoApple"]);//Add the image as attachment
[messageController addAttachmentData:dataImg typeIdentifier:@"public.data" filename:@"Image.png"];
[self presentViewController:messageController animated:YES completion:NULL];
}
}
Пожалуйста, найдите скриншот для того же.
Надеюсь, это сработает для вас !!!
я нашел это решение для меня:
if #available(iOS 10.0, *) {
UIApplication.shared.open(URL(string: "sms:123456789")!, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
if MFMessageComposeViewController.canSendText() {
if MFMessageComposeViewController.canSendAttachments() {
print("canSendAttachments")
}
let messageVC = MFMessageComposeViewController()
messageVC.body = "Enter a message";
messageVC.recipients = ["123456789"]
messageVC.messageComposeDelegate = self
messageVC.accessibilityActivate()
self.present(messageVC, animated: false, completion: nil)
} else {
print("Cant send sms")
}
}
accessibilityActivate()
приводит к тому, что отладчик выдает много AX Exchange error: Error Domain=Accessibility Code=0 "Remote service does not respond to _accessibilityMachPort" UserInfo={NSLocalizedDescription=Remote service does not respond to _accessibilityMachPort}
- person David; 18.07.2017