gpt4 book ai didi

ios - WhatsApp NSURL 在共享文本时返回 nil - Swift

转载 作者:可可西里 更新时间:2023-10-31 23:59:15 26 4
gpt4 key购买 nike

我正在尝试与 WhatsApp 共享文本,但 NSURL 始终返回 nil 但文本编码正确!看看我的代码:

var msg : NSString = "to the world of none";
var titlewithoutspace = msg.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
var urlWhats = NSString(string: "whatsapp://send?text=\(titlewithoutspace)")
println(urlWhats)
var whatsappURL = NSURL(string: urlWhats as String)
println(whatsappURL)

当我打印结果时,字符串等于:

whatsapp://send?text=Optional("to%20the%20world%20of%20none")

whatsappURL 总是返回 nil :

nil

最佳答案

stringByAddingPercentEscapesUsingEncoding: 返回一个可选的 String,这就是 urlWhats 包含 Optional("") 的原因。为了避免这种情况,你只需要像这样打开可选的:

var msg: NSString = "to the world of none";
var titlewithoutspace = msg.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
if let titlewithoutspace = titlewithoutspace {
var urlWhats = NSString(string: "whatsapp://send?text=\(titlewithoutspace)")
var whatsappURL = NSURL(string: urlWhats as String)
println(whatsappURL)
} else {
// Unwrapping failed because titlewithoutspace is nil (might be because stringByAddingPercentEscapesUsingEncoding failed).
}

此外,我建议您直接使用 String 类型,因为 NSString 对您来说毫无用处(除了 stringByAdding...):

var msg: NSString = "to the world of none";
var titlewithoutspace = msg.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
if let titlewithoutspace = titlewithoutspace {
var urlWhats = "whatsapp://send?text=\(titlewithoutspace)"
var whatsappURL = NSURL(string: urlWhats)
println(whatsappURL)
} else {
// Unwrapping failed because titlewithoutspace is nil (might be because stringByAddingPercentEscapesUsingEncoding failed).
}

另请注意,NSURL(string:) 可能会失败,因此它还会返回一个可选的 NSURL 对象。要使用它,您可能需要解包它,就像我对 titlewithoutspace 所做的那样。

关于ios - WhatsApp NSURL 在共享文本时返回 nil - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31720094/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com