2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Qiita全国学生対抗戦Advent Calendar 2023

Day 3

【SwiftUI】LinkPresentationを使ってTwitterの様なタイトル&OGP画像を簡単に表示する

Posted at

はじめに

昨日、「LinkPresentationを使ってURLからタイトルを取得する」という記事を書きました。

今日はLinkPresentationを使ってタイトル&OGP画像を簡単に表示させてみます。

サンプルアプリ

Simulator Screen Recording - iPhone 15 - 2023-12-03 at 22.23.17.gif

実装

ContentView.swift
import SwiftUI
import LinkPresentation

struct ContentView: View {
    @State private var url = ""
    
    @State private var metadata: LPLinkMetadata?
    
    var body: some View {
        List {
            Section {
                LabeledContent {
                    PasteButton(payloadType: String.self) { urls in
                        guard let url = urls.first else { return }
                        self.url = url
                    }
                    .labelStyle(.iconOnly)
                } label: {
                    TextField("URLを入力してください", text: $url)
                }
            }
            
            if let metadata {
                LPLinkSwiftUIView(metadata: metadata)
            }
        }
        .onChange(of: url) {
            Task {
                if let url = URL(string: url) {
                    metadata = try await fetchMetadata(url: url)
                }
            }
        }
    }
    
    private func fetchMetadata(url: URL) async throws -> LPLinkMetadata {
        let metadataProvider = LPMetadataProvider()
        return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<LPLinkMetadata, Error>) in
            metadataProvider.startFetchingMetadata(for: url) { metadata, error in
                if let error {
                    continuation.resume(throwing: error)
                } else if let metadata {
                    continuation.resume(returning: metadata)
                } else {
                    continuation.resume(throwing: LPError(.unknown))
                }
            }
        }
    }
}
LPLinkSwiftUIView.swift
import SwiftUI
import LinkPresentation

struct LPLinkSwiftUIView: UIViewRepresentable {
    var metadata: LPLinkMetadata
    
    func makeUIView(context: Context) -> LPLinkView {
        let view = LPLinkView(metadata: metadata)
        return view
    }
    
    func updateUIView(_ view: LPLinkView, context: Context) {
        view.metadata = metadata
    }
}

おわり

これ自作しようとすると大変そうですね
Appleが用意してくれてて助かります。

参考記事

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?