Skip to content

Instantly share code, notes, and snippets.

@samuelowino
Created August 11, 2024 21:25
Show Gist options
  • Select an option

  • Save samuelowino/b2f468382b7f6aeaf011ba235632be56 to your computer and use it in GitHub Desktop.

Select an option

Save samuelowino/b2f468382b7f6aeaf011ba235632be56 to your computer and use it in GitHub Desktop.
OpenGraph Swift Lib Sample
//
// ContentView.swift
// OpenGraphTrials
//
// Created by Samuel Owino on 11/08/2024.
//
import SwiftUI
import OpenGraph
struct ContentView: View {
@State var ogMetaModel = OpengraphMetaModel()
var body: some View {
VStack {
Text(ogMetaModel.title)
.frame(maxWidth: .infinity,alignment: .leading)
.font(.title)
if URL(string: ogMetaModel.imageUrl) != nil {
AsyncImage(url: URL(string: ogMetaModel.imageUrl)) { phase in
switch phase {
case .empty:
ProgressView()
case .success(let image):
image
.resizable()
.frame(maxWidth: .infinity,alignment: .center)
.aspectRatio(contentMode: .fit)
case .failure:
Image(systemName: "xmark.circle")
.resizable()
.aspectRatio(contentMode: .fit)
.foregroundColor(.red)
@unknown default:
EmptyView()
}
}
.frame(width: 200, height: 200)
}
Text(ogMetaModel.description)
.frame(maxWidth: .infinity,alignment: .leading)
.font(.subheadline)
Label(ogMetaModel.canonicalURL,systemImage: "globe")
.foregroundStyle(.tint)
.font(.caption)
.frame(maxWidth: .infinity,alignment: .leading)
}
.padding()
.background {
RoundedRectangle(cornerRadius: 12)
.stroke(.pink,lineWidth: 1.0)
}
.padding()
.onAppear {
OpenGraph.fetch(url: URL(string: "https://open.spotify.com/artist/2mLA48B366zkELXYx7hcDN?si=W5EHMsDDSSK24gxppb0u_g")!) { result in
switch result {
case .success(let og):
ogMetaModel.title = og[.title] ?? ""
ogMetaModel.description = og[.description] ?? ""
ogMetaModel.imageUrl = og[.image] ?? ""
ogMetaModel.canonicalURL = og[.url] ?? ""
case .failure(let error):
print(error)
}
}
}
}
}
struct OpengraphMetaModel{
var title: String = ""
var description: String = ""
var imageUrl: String = ""
var canonicalURL: String = ""
init(){}
init(title: String, description: String, imageUrl: String, canonicalURL: String) {
self.title = title
self.description = description
self.imageUrl = imageUrl
self.canonicalURL = canonicalURL
}
}
#Preview {
ContentView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment