MFMailComposeViewController throws an error only in iOS 9

后端 未结 5 1634
一生所求
一生所求 2020-12-15 18:33

I can\'t get MFMailComposeViewController to open without throwing a fatal error in iOS 9 Simulator.

The same code (Objective C) works flawlessly in iOS 8.x and lower

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-15 19:15

    As a simple work around for this problem, you can use "mailto" protocol, it will:

    • Not crash the app (device and simulator)
    • Prompt the user to login if the device has not login with any mail account

    Example in swift:

    Swift 3.0

    let mailRecipient = "support@abc.com"
    let mailSubject = "Help with ABC for iOS"
    let mailBody = "xxx"
    
    let mailTo = "mailto:\(mailRecipient)?subject=\(mailSubject)&body=\(mailBody)"
    
    guard let escapedMailTo = mailTo.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
        NSLog("Invalid mail to format")
        return
    }
    
    guard let url = NSURL(string: escapedMailTo) else {
        NSLog("Invalid mail to format: \(escapedMailTo)")
        return
    }
    
    UIApplication.sharedApplication().openURL(url)
    

    Swift 2.3

    let mailRecipient = "support@abc.com"
    let mailSubject = "Help with ABC for iOS"
    let mailBody = "xxx"
    
    let mailTo = "mailto:\(mailRecipient)?subject=\(mailSubject)&body=\(mailBody)"
    
    guard let escapedMailTo = mailTo.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()) else {
        NSLog("Invalid mail to format")
        return
    }
    
    guard let url = NSURL(string: escapedMailTo) else {
        NSLog("Invalid mail to format: \(escapedMailTo)")
        return
    }
    
    UIApplication.sharedApplication().openURL(url)
    

提交回复
热议问题