forked from programmingwithswift/ReadJSONFileURL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathViewController.swift
More file actions
82 lines (67 loc) · 2.39 KB
/
Copy pathViewController.swift
File metadata and controls
82 lines (67 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//
// ViewController.swift
// ReadJSONFileURL
//
// Created by ProgrammingWithSwift on 2020/03/22.
// Copyright © 2020 ProgrammingWithSwift. All rights reserved.
//
import UIKit
struct DemoData: Codable {
let title: String
let description: String
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let localData = self.readLocalFile(forName: "data") {
self.parse(jsonData: localData)
}
let urlString = "https://raw.githubusercontent.com/programmingwithswift/ReadJSONFileURL/master/hostedDataFile.json"
self.loadJson(fromURLString: urlString) { (result) in
switch result {
case .success(let data):
self.parse(jsonData: data)
case .failure(let error):
print(error)
}
}
// Do any additional setup after loading the view.
}
private func readLocalFile(forName name: String) -> Data? {
do {
if let bundlePath = Bundle.main.path(forResource: name,
ofType: "json"),
let jsonData = try String(contentsOfFile: bundlePath).data(using: .utf8) {
return jsonData
}
} catch {
print(error)
}
return nil
}
private func loadJson(fromURLString urlString: String,
completion: @escaping (Result<Data, Error>) -> Void) {
if let url = URL(string: urlString) {
let urlSession = URLSession(configuration: .default).dataTask(with: url) { (data, response, error) in
if let error = error {
completion(.failure(error))
}
if let data = data {
completion(.success(data))
}
}
urlSession.resume()
}
}
private func parse(jsonData: Data) {
do {
let decodedData = try JSONDecoder().decode(DemoData.self,
from: jsonData)
print("Title: ", decodedData.title)
print("Description: ", decodedData.description)
print("===================================")
} catch {
print("decode error")
}
}
}