Skip to content

Commit

Permalink
[refactor] #152 SwiftSoupProvider 로직 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
ShapeKim98 committed Nov 18, 2024
1 parent 70b704f commit 0a593a0
Showing 1 changed file with 17 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,53 +10,34 @@ import SwiftSoup

final class SwiftSoupProvider {
func parseOGTitle(_ url: URL) async throws -> String? {
return try await withCheckedThrowingContinuation { continuation in
do {
try parseOGMeta(url: url, type: "og:title", continuation: continuation)
} catch {
continuation.resume(throwing: error)
}
}
try await parseOGMeta(url: url, type: "og:title")
}

func parseOGImageURL(_ url: URL) async throws -> String? {
return try await withCheckedThrowingContinuation { continuation in
do {
try parseOGMeta(url: url, type: "og:image", continuation: continuation)
} catch {
continuation.resume(throwing: error)
}
}
try await parseOGMeta(url: url, type: "og:image")
}

func parseOGMeta(
url: URL,
type: String,
continuation: CheckedContinuation<String?, Error>
) throws {
func parseOGMeta(url: URL, type: String) async throws -> String? {
let html = try String(contentsOf: url)
let document = try SwiftSoup.parse(html)

if let metaData = try document.select("meta[property=\(type)]").first()?.attr("content") {
continuation.resume(returning: metaData)
return metaData
} else {
Task {
var request = URLRequest(url: url)
request.setValue(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
forHTTPHeaderField: "User-Agent"
)

let (data, _) = try await URLSession.shared.data(for: request)
guard let html = String(data: data, encoding: .utf8) else {
continuation.resume(returning: nil)
return
}
let document = try SwiftSoup.parse(html)
let metaData = try document.select("meta[property=\(type)]").first()?.attr("content")

continuation.resume(returning: metaData)
var request = URLRequest(url: url)
request.setValue(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
forHTTPHeaderField: "User-Agent"
)

let (data, _) = try await URLSession.shared.data(for: request)
guard let html = String(data: data, encoding: .utf8) else {
return nil
}
let document = try SwiftSoup.parse(html)
let metaData = try document.select("meta[property=\(type)]").first()?.attr("content")

return metaData
}
}
}

0 comments on commit 0a593a0

Please sign in to comment.