ios - 通过 URL 在 Whatsapp 上分享图像
问题描述
我正在使用 json 从我的 WordPress 网站创建图像应用程序,我正在使用 swift,我想从我的应用程序在 whatsapp 上共享图像,目前我尝试了这个代码它可以工作但只有图像名称我想从图像 url 共享图像,是那可能吗?
这是我的代码
let urlWhats = "whatsapp://app"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed) {
if let whatsappURL = URL(string: urlString) {
if UIApplication.shared.canOpenURL(whatsappURL as URL) {
if let image = UIImage(named: "splash") {
if let imageData = image.jpegData(compressionQuality: 1.0) {
let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")
do {
try imageData.write(to: tempFile, options: .atomic)
self.documentInteractionController = UIDocumentInteractionController(url: tempFile)
self.documentInteractionController.uti = "net.whatsapp.image"
self.documentInteractionController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)
} catch {
print(error)
}
}
}
} else {
// Cannot open whatsapp
}
}
}
谢谢
解决方案
首先,您应该从 URL 下载图像
- 创建一个函数来获取数据
func data(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
为此该怎么办->
let urlWhats = "whatsapp://app"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed) {
if let whatsappURL = URL(string: urlString) {
if UIApplication.shared.canOpenURL(whatsappURL as URL) {
// Set your image's URL into here
let url = URL(string: "https://your-image-url.com")!
data(from: url) { data, response, error in
guard let data = data, error == nil else { return }
DispatchQueue.main.async() { [weak self] in
let image = UIImage(data: data)
if let imageData = image.jpegData(compressionQuality: 1.0) {
let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")
do {
try imageData.write(to: tempFile, options: .atomic)
self.documentInteractionController = UIDocumentInteractionController(url: tempFile)
self.documentInteractionController.uti = "net.whatsapp.image"
self.documentInteractionController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)
} catch {
print(error)
}
}
}
}
} else {
// Cannot open whatsapp
}
}
}
推荐阅读
- html - Firefox div 像素化背景图像不起作用
- android - 致命异常:适配器中的 main (Recycler View Adapter)
- laravel - 如何从选择字段中获取值?
- java - 当我使用 setBounds 时,Jcomponents 的重绘方法会绘制一个白色矩形
- r - R:重命名矢量文件中的坐标
- java - checkstyle 自定义检查错误 无法实例化 com.mycompany.checks.MethodLimitCheck
- linux - 如何将视频时间添加到 ffmpeg 文件名?
- css - CSS 图像晕影效果
- android - 在 android webview 中处理 URI 以打开应用程序或重定向到 Playstore 始终显示 ERR_UNKNOWN_URL_SCHEME
- aws-sam - 我可以将 aws sam 模板文件拆分为多个文件吗?