1
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 2

【SwiftUI】LinkPresentationを使ってURLからタイトルを取得する

Last updated at Posted at 2023-12-02

はじめに

以前にURLからWebページのタイトルを取得するという記事を書きました。
https://qiita.com/SNQ-2001/items/7af62a202a6fbbf5167b

しかし、より良い方法を見つけたので記事にしておきます。

サンプルアプリ

Simulator Screen Recording - iPhone 15 - 2023-12-02 at 23.00.26.gif

実装

import SwiftUI
import LinkPresentation

struct ContentView: View {
    @State private var url = ""
    
    @State private var metadata: LPLinkMetadata?
    
    var body: some View {
        List {
            Section {
                TextField("URLを入力してください", text: $url)
            }
            
            if let title = metadata?.title {
                Section {
                    Text(title)
                } header: {
                    Text("タイトル")
                }
            }
        }
        .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))
                }
            }
        }
    }
}

おわり

LinkPresentationはOGPも表示できるようなのであとで試してみます

1
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
1
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?