OpenGraph is a Swift wrapper for OGP (Open Graph protocol).
You can fetch OpenGraph and get access to the attributes using subscript and enum cases as follows.
OpenGraph.fetch(url: url) { result in
switch result {
case .success(let og):
print(og[.title]) // => og:title of the web site
print(og[.type]) // => og:type of the web site
print(og[.image]) // => og:image of the web site
print(og[.url]) // => og:url of the web site
case .failure(let error):
print(error)
}
}
For macOS 10.15, iOS 13, watchOS 6, tvOS 13, and above, you can use the async/await syntax:
do {
let og = try await OpenGraph.fetch(url: url)
print(og[.title]) // => og:title of the web site
print(og[.type]) // => og:type of the web site
print(og[.image]) // => og:image of the web site
print(og[.url]) // => og:url of the web site
} catch {
print(error)
}
All metadata are defined here.
This library doesn't provide any platform specific views to display OGP data for high portability.
Furthermore, please copy the extension below to your own project if you want to use this library with the Rx interface.
extension Reactive where Base: OpenGraph {
static func fetch(url: URL?) -> Observable<OpenGraph> {
return Observable.create { observer in
guard let url = url else {
observer.onCompleted()
return Disposables.create()
}
OpenGraph.fetch(url: url) { result in
switch result {
case .success(let og):
observer.onNext(og)
case .failure(let error):
observer.onError(error)
}
observer.onCompleted()
}
return Disposables.create()
}
}
}
- Xcode 11.x / Swift 5.x (If you use Xcode 10.x, you can use 1.1.0.)
- iOS 10.0 or later
- macOS 10.9 or later
- tvOS 9.0 or later
- watchOS 2.0 or later
If you use Swift 2.2 or 2.3, use older version of OpenGraph.
Insert pod 'OpenGraph'
to your Podfile and run pod install
.
Insert github "satoshi-takano/OpenGraph"
to your Cartfile and run carthage update
.
In most cases, the OpenGraph can handle server-side redirections automatically. But some web pages provoke redirections on their front-end JavaScript.
You might be able to handle these kind of redirections by changing the User-Agent as follows.
#43
This library is under the MIT License.