Gmail是否可以通过UIapplication.shared.open url

时间:2019-02-07 15:46:35

标签: ios swift

Gmail客户端无法识别来自UIApplication.shared.openURL(url)的文本内的换行符

我有一个函数,该函数返回可用电子邮件客户端(由UIApplication.shared.canOpen验证)和相关URL的元组。它用于错误报告功能,因此arguments数组包含将自动填充电子邮件字段的文本。

启动这三个电子邮件客户端中的任何一个都没有问题,但是gmail是唯一不处理换行符的客户端。 gmail是否使用其他方法?

enum EmailClient {
    case gmail
    case outlook
    case mail

    var title: String {
        switch self {
        case .gmail: return "Gmail"
        case .outlook: return "Outlook"
        case .mail: return "Mail"
        }
    }

    //Creates url used by UIapplciation.shared to launch the client and autopopulate the email
    func url(error: CustomError?) -> URL? {

        guard let username = CredentialManager.username,
            let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else {
                return nil
        }

        let arguments = [
            username,
            UIDevice().modelName,
            UIDevice.current.systemVersion,
            appVersion,
            error?.description ?? "N/A" //When called from the settings page, no error is passed in
        ]

        var urlFormat: String

        switch self {
        case .gmail: urlFormat = "googlegmail:///co?to=%@&subject=%@&body=%@"
        case .outlook: urlFormat = "ms-outlook://compose?to=%@&subject=%@&body=%@"
        case .mail: urlFormat = "mailto:%@?subject=%@&body=%@"
        }

        return URL(string: String(format: urlFormat, arguments: [
            EMAIL_RECIPIENT,
            EMAIL_SUBJECT.replacingOccurrences(of: " ", with: "%20"),
            String(format: EMAIL_BODY_FORMAT, arguments: arguments).replacingOccurrences(of: " ", with: "%20").replacingOccurrences(of: "\n", with: "%0A")
        ]))
    }
}

2 个答案:

答案 0 :(得分:2)

1)将方案添加到您的info.plist

我们可以通过Info.plist文件这一美丽的东西来做到这一点。添加一个名为LSApplicationQueriesSchemes的新键作为数组。然后,您可以在阵列中输入您的应用程序。 Mail应用程序不需要进入这里,大概是因为它是Apple应用程序。您的输入应如下所示

image

func openGmail(withFrom: String?, withSubject: String?) {

    var gmailUrlString = "googlegmail:///"

    if let from = withFrom {
            gmailUrlString += "co?to=\(from)"
    }

    if let subject = withSubject {
        gmailUrlString += "&subject=\(subject)"
    }

}

我们需要做的最后一件事是对主题行进行URL编码,然后再将其传递给URL。我们可以通过在字符串上调用subjectString?.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)来做到这一点。

答案 1 :(得分:0)

似乎使用“ \ r \ n”而不是“ \ n”可以解决问题