当用户在我的新闻聚合器中发送文章链接时,我正在尝试自定义链接预览,该聚合器内置在 SwiftUI 中。
我正在使用从发布者的网站获取缩略图图像LPMetadataProvider
,然后使用该图像创建我自己的LPLinkMetadata
对象以及我提供的其他元数据。即“显示纽约时报的文章图像缩略图,但当用户在他们的消息应用程序中点击链接预览时,将用户深层链接到我的应用程序中的文章”。
我可以提供没有图像的预览,它可以深层链接到我的应用程序,或者图像本身,没有深层链接。我怎样才能得到两者?
public class LinkPresentationItemSource: NSObject, UIActivityItemSource {
public var metadata: LPLinkMetadata?
public var articleID: String
public var title: String
public var imageUrl: String
enum Constant {
static let deepLinkURLSchemeAndHost = "https://www.somedeeplinkurl.com/"
}
private func createDeepLinkURLFrom(id: String?) -> String {
guard let selectedArticleID = id else {
return ""
}
return Constant.deepLinkURLSchemeAndHost + selectedArticleID
}
// Prepare data to share
public func activityViewControllerLinkMetadata(
_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
let lpLinkMetadataProvider = LPMetadataProvider()
let lpLinkMetadata = LPLinkMetadata()
guard let imageUrl = URL(string: imageUrl) else {
return nil
}
lpLinkMetadataProvider.startFetchingMetadata(for: imageUrl) { metadata, _ in
guard let metadata = metadata else {
return
}
DispatchQueue.main.async {
lpLinkMetadata.imageProvider = NSItemProvider(contentsOf: metadata.url)
}
}
guard let originalURL = URL(string: createDeepLinkURLFrom(id: articleID)) else {
return nil
}
lpLinkMetadata.originalURL = originalURL
lpLinkMetadata.url = lpLinkMetadata.originalURL
lpLinkMetadata.title = title
metadata = lpLinkMetadata
return lpLinkMetadata
}
// Placeholder for real data, we don't care in this example so just return a simple string
public func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return "Placeholder"
}
/// Return the data will be shared
/// - Parameters:
/// - activityType: Ex: mail, message, airdrop, etc..
public func activityViewController(_ activityViewController: UIActivityViewController,
itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
guard let metadata = metadata else {
return nil
}
return metadata.url
}
public init(articleID: String, imageUrl: String, title: String) {
self.articleID = articleID
self.imageUrl = imageUrl
self.title = title
}
}
具体来说,以下方法中返回的内容似乎不包括我提供的所有元数据。如果我返回metadata
或LPLinkPreview(metadata: metadata)
消息应用程序根本没有填充任何链接预览:
public func activityViewController(_ activityViewController: UIActivityViewController,
itemForActivityType activityType: UIActivity.ActivityType?) -> Any?