从我的应用打开Gmail应用

我试图从我的应用程序发送电子邮件。 但是,我想要的是,如果用户在他/她的手机上有Gmail应用程序,则应该使用它发送邮件。 如果Gmail应用程序不可用,则应将用户redirect到邮箱。

那么如何知道用户是否包含Gmail应用程序,以及如何将用户redirect到该应用程序。

您需要使用自定义URL Scheme。 对于Gmail应用程序:

googlegmail:// 

如果你想编写一个消息,你可以添加更多的参数到这个URL:

 co?subject=Example&body=ExampleBody 

你可以确定是否使用这个代码安装了任何types的应用程序(只需将customURLreplace为其他应用程序):

 NSString *customURL = @"googlegmail://"; if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]]) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]]; } else { //not installed, show popup for a user or an error } 

安装iOS9 +

如此处所述, 如果您使用的是iOS9 + ,请不要忘记将googlegmail添加到info.plist上的LSApplicationQueriesSchemes

我的info.plist

打开GMail的代码

然后,你可以做同样的答案(下面是我的swift 2.3版本):

 let googleUrlString = "googlegmail:///co?subject=Hello&body=Hi" if let googleUrl = NSURL(string: googleUrlString) { // show alert to choose app if UIApplication.sharedApplication().canOpenURL(googleUrl) { if #available(iOS 10.0, *) { UIApplication.sharedApplication().openURL(googleUrl, options: [:], completionHandler: nil) } else { UIApplication.sharedApplication().openURL(googleUrl) } } }