在我的iOS应用程序中,我想添加一个功能,该功能会将邀请发送给在其他应用程序(如WhatsApp或其他消息服务)中选择的人员。我不知道该怎么做。请在这方面帮助我。一些指导将不胜感激。
我尝试使用WhatsApp发送邀请。但是我无法实现。
@IBAction func invite(_ sender: UIButton) {
let ReferCode = UserDefaults.standard.string(forKey: "ReferCode") ?? ""
let originalString = ReferCode
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed)
let url = URL(string: "whatsapp://send?text= Your referral code is\(escapedString!)")
if UIApplication.shared.canOpenURL(url! as URL)
{
if #available(iOS 10.0, *) {
UIApplication.shared.open(url! as URL, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
}
}
}
当我按下邀请按钮时,应用程序崩溃了。
答案 0 :(得分:0)
如果您在nil
中获得referCode
值,则可能会崩溃。使用条件解包获得可选值。
@IBAction func invite(_ sender: UIButton) {
guard let referCode = UserDefaults.standard.string(forKey: "ReferCode") else {
debugPrint("referCode not available")
return
}
let escapedString = referCode.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed)
guard let url = URL(string: "whatsapp://send?text= Your referral code is \(String(describing: escapedString))") else {
debugPrint("URL not correct")
return
}
if UIApplication.shared.canOpenURL(url)
{
if #available(iOS 10.0, *) {
UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
}
}
}