-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebPageMetadataService.swift
More file actions
63 lines (52 loc) · 1.99 KB
/
Copy pathWebPageMetadataService.swift
File metadata and controls
63 lines (52 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//
// WebPageMetadataService.swift
// DevLog
//
// Created by 최윤진 on 2/9/26.
//
import Foundation
import LinkPresentation
final class WebPageMetadataService {
func fetchMetadata(from response: WebPageResponse) async throws -> WebPageMetadata {
guard let url = URL(string: response.urlString) else {
throw URLError(.badURL)
}
let provider = LPMetadataProvider()
provider.timeout = 10.0
let metadata = try await provider.startFetchingMetadata(for: url)
let imageURL = try await extractImageURL(from: metadata.imageProvider, url: url)
return WebPageMetadata(
title: metadata.title,
url: url,
displayURL: metadata.url ?? url,
imageURL: imageURL
)
}
private func extractImageURL(from imageProvider: NSItemProvider?, url: URL) async throws -> URL? {
guard let imageProvider else { return nil }
return try await withCheckedThrowingContinuation { continuation in
imageProvider.loadObject(ofClass: UIImage.self) { image, error in
guard let image = image as? UIImage,
let data = image.jpegData(compressionQuality: 1.0) else {
continuation.resume(returning: nil)
return
}
guard let fileName = url.absoluteString.addingPercentEncoding(
withAllowedCharacters: .alphanumerics
) else {
continuation.resume(returning: nil)
return
}
let tempURL = FileManager.default.temporaryDirectory
.appendingPathComponent(fileName)
.appendingPathExtension("jpeg")
do {
try data.write(to: tempURL)
continuation.resume(returning: tempURL)
} catch {
continuation.resume(throwing: error)
}
}
}
}
}