【Unity】ファイル添付してメーラーを起動する
#Unity #iOS
黒羽のアリカでエラーログをメール添付して送る機能を作っていたときのメモ
もともとApplication.OpenURLでmailtoスキーマを開いていたが、ファイル添付をしたかったので自作した
結論
iOSのNative Pluginを作って、MFMailComposeViewControllerを呼び出す
externメソッドを呼ぶ際にファイルのパスを渡す
code: Plugins/iOS/HxMail.mm
#import <MessageUI/MessageUI.h>
extern "C" {
@interface HXMailComposeViewDelegate : NSObject<MFMailComposeViewControllerDelegate>
@end
@implementation HXMailComposeViewDelegate
- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
UnityGetGLViewController() dismissViewControllerAnimated:YES completion:nil;
}
@end
void Hexat_Send_Mail_With_File (const char *to, const char *title, const char *message, const char *logfileUrl) {
MFMailComposeViewController *picker = [MFMailComposeViewController alloc init];
auto path = NSString stringWithCString:logfileUrl encoding:NSUTF8StringEncoding;
auto basename = [path componentsSeparatedByString:@"/" lastObject];
auto file = [NSData dataWithContentsOfFile:NSString stringWithCString:logfileUrl encoding:NSUTF8StringEncoding];
[picker setToRecipients:@NSString stringWithCString:to encoding:NSUTF8StringEncoding];
picker addAttachmentData:file mimeType:@"text/plain" fileName:basename;
[picker setSubject:NSString stringWithCString:title encoding:NSUTF8StringEncoding];
[picker setMessageBody:NSString stringWithCString:message encoding:NSUTF8StringEncoding isHTML:false];
auto del = [HXMailComposeViewDelegate alloc init];
picker.mailComposeDelegate = del;
UnityGetGLViewController() presentViewController:picker animated:YES completion: nil;
}
}
code: Mail.cs
#if UNITY_IOS
DllImport("__Internal")
private static extern void Hexat_Send_Mail_With_File(
string to, string title, string message, string logFileUrl
);
#endif
public static void Mail(string to, string title, string message, string logFileUrl)
{
#if UNITY_IOS && !UNITY_EDITOR
Hexat_Send_Mail_With_File(to, title, message, logFileUrl);
#endif
}
注意
iOSでしか動きません
ファイルが大きすぎるとどうなるかは知りません