I'm using this documentation as my base https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation
I'm failing to understand how I would simply adapt the app to load the json remotely
import Foundation
var landmarks: [Landmark] = load("landmarkData.json")
func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main
snippet from Model data.swift
the only example I've found is included below, however it's using an entirely different setup and does not use a detail view.
import SwiftUI
import Combine
struct ContentView: View {
@ObservedObject var fetcher = MovieFetcher()
var body: some View {
VStack {
List(fetcher.movies) { movie in
VStack (alignment: .leading) {
Text(movie.name)
Image(movie.thumbnail)
Text(movie.released)
.font(.system(size: 11))
.foregroundColor(Color.gray)
}
}
}
}
}
public class MovieFetcher: ObservableObject {
@Published var movies = [Movie]()
init(){
load()
}
func load() {
let url = URL(string: "https://wolvideos.web.app/videos.js")!
URLSession.shared.dataTask(with: url) {(data,response,error) in
do {
if let d = data {
let decodedLists = try JSONDecoder().decode([Movie].self, from: d)
DispatchQueue.main.async {
self.movies = decodedLists
}
}else {
print("No Data")
}
} catch {
print ("Error")
}
}.resume()
}
}
struct Movie: Codable, Identifiable {
public var id: Int
public var name: String
public var thumbnail: String
public var released: String
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
case thumbnail = "thumbnail"
case released = "description"
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
If possible can someone explain how and the best way to load a json file and then let the app format it into detail views?
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
it's infuriating that it sometimes only takes 2 minuets and then takes hours on other devices. knowing how long it's going to take would actually give us information to make adjustments.
I'm. asking this one to see how many other developers would also like this feature, and to see if anyone knows of an add-on or such.
I've followed several tutorials and nothing works or is remotely simple. can anyone perhaps link a json tutorial that can load the following in a "SWIFT UI" format?
{
"id": 182,
"name": "message 2048",
"interactive": "https://wolvideos.firebaseapp.com/Test1.mp4",
"thumbnail": "https://wolvideos.firebaseapp.com/back.jpg",
"date": "April 1",
"videolink": "https://player.vimeo.com/external/656370948.m3u8?s=e50ca2b440798886646ba88a07e9c46a90c9df11",
"sharelink": "https://youtu.be/n7YjxFCyDNQ"
},
{
"id": 180,
"name": "Title 4",
"interactive": "https://wolvideos.firebaseapp.com/Test2.mp4",
"thumbnail": "https://wolvideos.firebaseapp.com/back.jpg",
"date": "April 2",
"videolink": "https://player.vimeo.com/external/653500077.m3u8?s=96c687bef62bfd01ea195e4113e197ebd8d09143",
"sharelink": "https://youtu.be/n7YjxFCyDNQ"
},
{
"id": 172,
"name": "Titil 20203",
"interactive": "https://wolvideos.firebaseapp.com/Test1.mp4",
"thumbnail": "https://wolvideos.firebaseapp.com/back.jpg",
"date": "April 1",
"videolink": "https://player.vimeo.com/external/656370948.m3u8?s=e50ca2b440798886646ba88a07e9c46a90c9df11",
"sharelink": "https://youtu.be/n7YjxFCyDNQ"
},
{
"id": 171,
"name": "Title 20part2",
"interactive": "https://wolvideos.firebaseapp.com/Test2.mp4",
"thumbnail": "https://wolvideos.firebaseapp.com/back.jpg",
"date": "April 2",
"videolink": "https://player.vimeo.com/external/653500077.m3u8?s=96c687bef62bfd01ea195e4113e197ebd8d09143",
"sharelink": "https://youtu.be/n7YjxFCyDNQ"
},
{
"id": 170,
"name": "Title 2021",
"interactive": "https://wolvideos.firebaseapp.com/Test1.mp4",
"thumbnail": "https://wolvideos.firebaseapp.com/back.jpg",
"date": "April 1",
"videolink": "https://player.vimeo.com/external/656370948.m3u8?s=e50ca2b440798886646ba88a07e9c46a90c9df11",
"sharelink": "https://youtu.be/n7YjxFCyDNQ"
},
{
"id": 169,
"name": "Title 2020",
"interactive": "https://wolvideos.firebaseapp.com/Test2.mp4",
"thumbnail": "https://wolvideos.firebaseapp.com/back.jpg",
"date": "April 2",
"videolink": "https://player.vimeo.com/external/653500077.m3u8?s=96c687bef62bfd01ea195e4113e197ebd8d09143",
"sharelink": "https://youtu.be/n7YjxFCyDNQ"
}
]
https://wolvideos.firebaseapp.com/Simple.json
Oddly the tab view does not respect the color assigned to the background by default (being black in this case), is this something that I need to define a glitch I should submit in feedback?
is it possible to load a link such as
Link("Apple", destination: URL(string: "https://www.apple.com")!)
from a tab bar item? if so how?
struct MainView: View {
@State private var selectedTab = "Three"
var body: some View {
TabView(selection: $selectedTab) {
LiveView()
.tabItem {
Label("LIVE", systemImage: "camera.metering.center.weighted")
.font(Font.title.weight(.ultraLight))
}
.tag("One")
if I add an link or text I get errors. I appreciate any help!
I'm running on fumes but logically this view should be showing the share button on the bottom right, and the Title/Date/PlayButton in the middle? What am I doing wrong? It currently just shows the share button underneath
import SwiftUI
import AVKit
struct ContentView: View {
@State private var items = [Item]()
@State private var currentPage = 0
var body: some View {
TabView(selection: $currentPage) {
ForEach(items, id: \.id) { item in
VideoPlayerView(url: item.interactive)
.aspectRatio(contentMode: .fill)
.tag(item.id)
.onAppear {
let controller = AVPlayerViewController()
controller.player = AVPlayer(url: URL(string: item.interactive)!)
controller.showsPlaybackControls = false
controller.player?.play()
}
.overlay(
VStack() {
Spacer()
Text(item.name)
.font(.title)
Text(item.date)
.font(.caption)
Button(action: {
let player = AVPlayer(url: URL(string: item.videolink)!)
let playerController = AVPlayerViewController()
playerController.player = player
playerController.showsPlaybackControls = true
UIApplication.shared.windows.first?.rootViewController?.present(playerController, animated: true, completion: {
player.play()
})
}) {
HStack(spacing: 5) {
Text("PLAY")
Image(systemName: "play.circle")
}
.padding(.horizontal, 10)
.padding(.vertical, 5)
.background(Color.white)
.foregroundColor(.black)
.cornerRadius(20)
}
Button(action: {
let activityVC = UIActivityViewController(activityItems: [URL(string: item.sharelink)!], applicationActivities: nil)
UIApplication.shared.windows.first?.rootViewController?.present(activityVC, animated: true, completion: nil)
}) {
Image(systemName: "square.and.arrow.up.circle")
.foregroundColor(.black)
}
.padding(.bottom, 50)
}
)
}
}
.tabViewStyle(.page)
.onAppear(perform: loadData)
.gesture(DragGesture()
.onEnded { value in
let offset = value.translation.width / UIScreen.main.bounds.width
let newIndex = (CGFloat(currentPage) - offset).rounded()
currentPage = min(max(Int(newIndex), 0), items.count - 1)
}
)
}
func loadData() {
guard let url = URL(string: "jsonfile") else { return }
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
let items = try decoder.decode([Item].self, from: data)
DispatchQueue.main.async {
self.items = items
}
} catch {
print(error.localizedDescription)
}
}.resume()
}
}
struct VideoPlayerView: UIViewRepresentable {
let url: String
func makeUIView(context: Context) -> AVPlayerView {
let view = AVPlayerView()
view.playerLayer.player = AVPlayer(url: URL(string: url)!)
view.playerLayer.videoGravity = .resizeAspectFill
view.playerLayer.backgroundColor = UIColor.black.cgColor
view.playerLayer.player?.play()
return view
}
func updateUIView(_ uiView: AVPlayerView, context: Context) {
// Nothing to update
}
}
class AVPlayerView: UIView {
override class var layerClass: AnyClass {
return AVPlayerLayer.self
}
var playerLayer: AVPlayerLayer {
return layer as! AVPlayerLayer
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let hitView = super.hitTest(point, with: event)
return hitView == self ? nil : hitView
}
}
struct Item: Codable, Identifiable {
let id: Int
let name: String
let interactive: String
let thumbnail: String
let date: String
let videolink: String
let sharelink: String
}
I cant get either a custom of basic color to not timeout Xcode
.listRowBackground( Capsule().fill(Color(white: 1, opacity(0.8))) .padding(.vertical, 2) .padding(.horizontal, 10) )
the file does not show a black fill but the app shows a black circle.
since it's to long https://gist.github.com/YutaTheTraveler/0b8c11faf997f2118d19bbd009d490ba.js
This video session is essentially a consumer facing video, there isn't even a single line of code shown.
VideoPlayer(player: player)
doesn't give the shown "new features" by default, an example / implementation should be expected of a WWDC session.
I've been watching various tutorials and have managed to come up with the following code:
import SwiftUI
import AVKit
struct ContentView: View {
@State private var wolData = [Main]()
var body: some View {
NavigationView{List(wolData, id: \.id) { item in
NavigationLink(destination: MainDetail(json: item)) {
HStack() {
Text(item.name)
.font(.headline)
Text(item.date)
.font(.footnote)
if #available(iOS 15.0, *) {
AsyncImage(url: URL(string: item.thumbnail))
{ image in
image
.resizable()
.scaledToFill()
} placeholder: {
Color.purple.opacity(0.1)
}
.frame(width: 20, height: 20)
} else {
// Fallback on earlier versions
}
}
}
}.onAppear(perform: loadData)}
}
}
extension ContentView
{
func loadData() {
guard let url = URL(string: "https://wolvideos.firebaseapp.com/Simple.json") else {
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let response_obj = try? JSONDecoder().decode([Main].self, from: data) {
DispatchQueue.main.async {
self.wolData = response_obj
}
}
}
}.resume()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import Foundation
struct Main: Decodable {
var id: Int
var name: String
var interactive: String
var thumbnail: String
var date: String
var videolink: String
var sharelink: String
}
import SwiftUI
import AVKit
struct MainDetail: View {
var json: Main
private let player = AVPlayer(url: URL(string: "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8")!)
var body: some View {
VideoPlayer(player: player)
.onAppear() {
// Start the player going, otherwise controls don't appear
player.play()
}
.onDisappear() {
// Stop the player when the view disappears
player.pause()
}
}
}
Now that I've shared that, the intent is to when the user clicks an option load the corresponding video (from the json not the current test file) via HLS in a default player (like the one in safari)... should I be going about this in a different way? I'm starting to think committing to SwiftUI is a mistake.
I'm attempting to simply pass the video link inside the json to the navigation menu... my brain is fried as I'm lost in why I can't do this view the navigation link protocol.
import SwiftUI
import AVKit
struct MainDetail: View {
var json: Main
private let player = AVPlayer(url: URL(string: item.interactive))
var body: some View {
VideoPlayer(player: player)
.onAppear() {
// Start the player going, otherwise controls don't appear
player.play()
}
.onDisappear() {
// Stop the player when the view disappears
player.pause()
}
}
}
this returns a "Cannot find 'item' in scope" despite being declared back on the main content view. the intended action is loading the "interactive" link (m3u8 file) in a player view when clicked on. I apologize for not understanding what's going on here.
I can only find UIKit examples that don't work when used... I would prefer to never use appdelgate again.
here is the code:
struct LiveView: View {
@State var allowsInlineMediaPlayback: Bool = false
var body: some View {
VStack {
VideoView(videoID:"vimeo.com/event/000000/embed")
}
}
}
struct VideoView: UIViewRepresentable {
let videoID: String
func makeUIView(context: Context) -> WKWebView {
let configuration = WKWebViewConfiguration()
configuration.allowsInlineMediaPlayback = true
let WKWebView = WKWebView(frame: .zero, configuration: configuration)
return WKWebView
}
func updateUIView(_ uiView: WKWebView, context: Context) {
guard let youtubeURL = URL(string: "https://\(videoID)") else
{return}
uiView.load(URLRequest (url: youtubeURL))
}
}
Is their a better way to accomplish feeding a live event link into a playerview instead of needing a WKWebView?
I'm very frustrated. Why does the code work on the iPhone but iPad completely disregards anything code modifying MapKit?
import SwiftUI
import MapKit
struct MapView: View {
var coordinate: CLLocationCoordinate2D
@State private var region = MKCoordinateRegion()
var body: some View {
Map(coordinateRegion: $region)
.edgesIgnoringSafeArea(.all)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onAppear {
setRegion(coordinate)
}
}
private func setRegion(_ coordinate: CLLocationCoordinate2D) {
region = MKCoordinateRegion(
center: coordinate,
span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
)
}
}
struct MapView_Previews: PreviewProvider {
static var previews: some View {
MapView(coordinate: CLLocationCoordinate2D(latitude: 34.000, longitude: -116.000))
.previewDevice(PreviewDevice(rawValue: "iPhone 12 Pro Max"))
}
}
my mind is shot. core data hasn't been my cup of tea.
print("saveTrigger called with trigger: \(trigger)")
let encoder = JSONEncoder()
let fm = FileManager.default
let documentsDirectory = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
let reflectionsURL = documentsDirectory.appendingPathComponent("reflections.json")
let triggersDirectory = documentsDirectory.appendingPathComponent("Triggers")
// Create a new reflections file if it doesn't exist
if !fm.fileExists(atPath: reflectionsURL.path) {
let emptyData = Data()
fm.createFile(atPath: reflectionsURL.path, contents: emptyData, attributes: nil)
}
// Write the trigger to the reflections file
do {
let data = try encoder.encode(trigger)
try data.write(to: reflectionsURL)
print("Trigger saved to device: \(trigger)")
print("Reflections file URL: \(reflectionsURL)")
} catch {
print("Failed to save trigger: \(error)")
}
// Find the trigger file with the UUID inside the file
let triggerFileURL = triggersDirectory.appendingPathComponent("\(trigger.id).json")
if fm.fileExists(atPath: triggerFileURL.path) {
do {
let data = try Data(contentsOf: triggerFileURL)
let uuid = try JSONDecoder().decode(UUID.self, from: data)
let uuidString = uuid.uuidString
let matchingTriggerFileURL = triggersDirectory.appendingPathComponent("\(uuidString).json")
if fm.fileExists(atPath: matchingTriggerFileURL.path) {
try fm.removeItem(at: matchingTriggerFileURL)
print("Trigger file deleted: \(matchingTriggerFileURL.lastPathComponent)")
} else {
print("Trigger file not found")
}
} catch {
print("Error deleting trigger file: \(error.localizedDescription)")
}
} else {
print("Trigger file not found")
}
}