-
-
Notifications
You must be signed in to change notification settings - Fork 366
/
TextViewController.swift
73 lines (57 loc) · 2.54 KB
/
TextViewController.swift
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
//
// TextViewController.swift
// netfox_ios_demo
//
// Created by Nathan Jangula on 10/12/17.
// Copyright © 2017 kasketis. All rights reserved.
//
import UIKit
class TextViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
var session: URLSession!
var dataTask: URLSessionDataTask?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBAction func tappedLoad(_ sender: Any) {
dataTask?.cancel()
if session == nil {
session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
}
guard let url = URL(string: "https://api.chucknorris.io/jokes/random") else { return }
let request = URLRequest(url: url)
dataTask = session.dataTask(with: request) { (data, response, error) in
if let error = error {
self.handleCompletion(error: error.localizedDescription, data: data)
} else {
guard let data = data else { self.handleCompletion(error: "Invalid data", data: nil); return }
guard let response = response as? HTTPURLResponse else { self.handleCompletion(error: "Invalid response", data: data); return }
guard response.statusCode >= 200 && response.statusCode < 300 else { self.handleCompletion(error: "Invalid response code", data: data); return }
self.handleCompletion(error: error?.localizedDescription, data: data)
}
}
dataTask?.resume()
}
private func handleCompletion(error: String?, data: Data?) {
DispatchQueue.main.async {
if let error = error {
NSLog(error)
return
}
if let data = data {
do {
let dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
if let message = dict?["value"] as? String {
self.textView.text = message
}
} catch {
}
}
}
}
}
extension TextViewController : URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
}
}