我正在创建一个通过社交媒体平台(尤其是在WhatsApp上)共享图像的应用程序。我尝试使用UIActivityViewController
,但显示工作表时它不显示WhatsApp选项。我在线搜索并找到下面的代码:显示工作表时,它显示WhatsApp选项,但是选择WhatsApp选项会导致应用程序崩溃。这是代码:
let controller = UIDocumentInteractionController()
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true)
let documentDir = path[0] as String
let imgPath=documentDir.stringByAppendingPathComponent("tmp_flag.png")
let imageURL = NSURL.fileURLWithPath(imgPath)
println("Image path :\(imageURL)")
controller.delegate = self
controller.UTI = "net.whatsapp.image"
controller.URL = imageURL!
controller.presentOpenInMenuFromRect(CGRectZero, inView: self.view, animated: true)
谁能在某个地方发现任何错误?如果没有,是否有人知道如何使其工作?
最佳答案
在Swift 3中使用此代码
@IBAction func whatsappShareWithImages(_ sender: AnyObject) {
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: "whatsappIcon") {
if let imageData = UIImageJPEGRepresentation(image, 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 {
print("Cannot open whatsapp")
}
}
}
}
将此代码添加到您的应用程序
**plist**
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>
您也可以参考小型应用程序以获取参考:https://github.com/nithinbemitk/iOS-Whatsapp-Share
关于ios - 使用Swift在WhatsApp上共享图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28492869/