如何从 iPhone (swift) 应用程序打开 WhatsApp?

2024-01-18

我在用webview对于我的 Swift 应用程序,我有"Share on WhatsApp"我的网站上的按钮在浏览器上运行良好。但在 iPhone 应用程序上,当我点击按钮时,没有任何反应。

如何从我的应用程序打开 WhatsApp?我在用Xcode 8 and iOS 10.


适用于 Swift 4.2+ 和 iOS 9+

方法 1:(启动 WhatsApp 应用程序(如果已安装))

let phoneNumber =  "+989160000000" // you need to change this number
let appURL = URL(string: "https://api.whatsapp.com/send?phone=\(phoneNumber)")!
if UIApplication.shared.canOpenURL(appURL) {
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(appURL, options: [:], completionHandler: nil)
    }
    else {
        UIApplication.shared.openURL(appURL)
    }
}

方法二:(使用safari打开WhatsApp短链接网页)

let phoneNumber =  "+989160000000" // you need to change this number
let appURL = URL(string: "https://wa.me/\(phoneNumber)")!
if UIApplication.shared.canOpenURL(appURL) {
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(appURL, options: [:], completionHandler: nil)
    } else {
        UIApplication.shared.openURL(appURL)
    }
}

注意:电话号码中的“+”即可。

您可以结合使用这两种方法:

func createWhatsappURL(phoneNumber: String) -> URL {
    return URL(string: "https://api.whatsapp.com/send?phone=\(phoneNumber)")!
}

func createWebWhatsappURL(phoneNumber: String) -> URL {
    return URL(string: "https://wa.me/\(phoneNumber)")!
}

func openURL(_ url: URL) {
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    } else {
        UIApplication.shared.openURL(url)
    }
}

func openWhatsapp(withPhoneNumber phoneNumber: String) {
    let appURL = createWhatsappURL(phoneNumber: phoneNumber)
    let webURL = createWebWhatsappURL(phoneNumber: phoneNumber)
    
    if UIApplication.shared.canOpenURL(appURL) {
        openURL(appURL)
    } else {
        openURL(webURL)
    }
}

// usage
let phoneNumber = "+989160000000" // you need to change this number
openWhatsapp(withPhoneNumber: phoneNumber)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从 iPhone (swift) 应用程序打开 WhatsApp? 的相关文章

随机推荐