您可以使用NSDataDetector鏈接類型NSTextCheckingResult.CheckingType.link
。你只需要下載URL數據,並從中得到所有的鏈接匹配:
extension String {
var detectURLs: [URL] {
return (try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue))?
.matches(in: self, range: NSRange(location: 0, length: utf16.count))
.flatMap{ $0.url } ?? []
}
}
extension Data {
var string: String { return String(data: self, encoding: .utf8) ?? "" }
}
遊樂場測試:
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
// add the extensions above here
URLSession.shared.dataTask(with: URL(string: "http://www.example.com/downloads/")!) { data, response, error in
guard let data = data, error == nil else { return }
let pdfs = data.string.detectURLs.filter{$0.pathExtension.lowercased() == "pdf"}
print(pdfs) // print(urls) // "[http://www.sample-videos.com/pdf/Sample-pdf-5mb.pdf]\n"
}.resume()
這是偉大的!但有沒有任何可能的方式來基於文件過濾鏈接?例如我需要鏈接,其中包含'.pdf' –
是的我需要鏈接,包含文件,如:pdf,mp4,mp3等... –
是的,確實... –