我正在尝试从我的应用发送电子邮件。发送电子邮件窗口打开时,未设置收件人和正文。每当我尝试按任何字段来编辑它们时,我的应用程序崩溃并给我这个错误:
***断言失败 - [UIKeyboardTaskQueue waituntilalltasksarefinished],/sourcuecache / UIKIt_Sim / UIKit-3318.16.14 / KeyTothQaskue.m:374 由于未捕获的异常终止应用程序' NSInternalInconsistencyException',原因:'仅在主线程上运行!
我查看了电子邮件教程,但无法找到我做错的事情。代码已添加供参考:
if ([MFMailComposeViewController canSendMail]) {
// Get current date/time
NSDate *date = picker.date;
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc]init];
mailer.mailComposeDelegate = self;
mailer.modalPresentationStyle = UIModalPresentationCurrentContext;
// Set title
NSDateFormatter *dateFmt = [[NSDateFormatter alloc] init];
[dateFmt setDateStyle:NSDateFormatterMediumStyle];
[mailer setSubject:[NSString stringWithFormat:@"test email: sent on %@", [dateFmt stringFromDate:date]]];
// Set recipient
[mailer setToRecipients:@[@"testingEmail@example.com"]];
// Set attachment
CGRect r = CGRectMake(0, 0, 200, 200);
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
UIGraphicsBeginImageContextWithOptions(r.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(r.size);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), - mapview.center.x + r.size.width / 2.f, - mapview.center.y + r.size.height / 2.f);
[mapholder.layer renderInContext:c];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(img);
[mailer addAttachmentData:imageData mimeType:@"image/png" fileName:@"map"];
// Set email body
[dateFmt setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
CLLocationCoordinate2D loc = mapview.centerCoordinate;
NSString *emailBody = [NSString stringWithFormat:@"BRO it is Time: %@\n Location: %f,%f", [dateFmt stringFromDate:date], loc.latitude, loc.longitude];
[mailer setMessageBody:emailBody isHTML:NO];
[self presentViewController:mailer animated:YES completion:nil];
}
和
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[self dismissModalViewControllerAnimated:YES];
}
答案 0 :(得分:1)
你的例外说,原因:'只在主线程上运行
使用以下命令检查代码是否在后台队列上运行:
NSLog(@"%@",[NSOperationQueue currentQueue]);
它应该在主队列中运行。如果没有尝试将代码包装在:
dispatch_async(dispatch_get_main_queue(), ^{
...
});
答案 1 :(得分:1)
您无法在后台线程上显示UI。通常,您不应该对后台线程执行任何UIKit
工作。通过在后台线程上调用像(UIImagePNGRepresentation
)这样的重型映像API,您处于正确的轨道上。完成创建屏幕截图等后,需要调度到主队列以显示邮件视图控制器。
// Create mail composer with screenshots etc
// ...
// Now present mail composer on "MAIN" thread
dispatch_async(dispatch_get_main_queue(), ^{
[self presentViewController:mailer animated:YES completion:nil];
}