Last active
September 30, 2020 20:32
-
-
Save kafkaesqu3/39d337d68994d57d2e37b10aa95a4972 to your computer and use it in GitHub Desktop.
demonstration of HTTP GET requests in swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.swift | |
// HTTPGet | |
// | |
// Created by david on 9/30/20. | |
// | |
import Foundation | |
func async_req() -> Void { | |
let url = URL(string: "http://example.com")! | |
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in | |
guard let data = data else { return } | |
print(String(data: data, encoding: .utf8)!) | |
} | |
task.resume() | |
//wait for task to complete | |
RunLoop.main.run() | |
} | |
extension URLSession { | |
func synchronousDataTask(urlrequest: URLRequest) -> (data: Data?, response: URLResponse?, error: Error?) { | |
var data: Data? | |
var response: URLResponse? | |
var error: Error? | |
let semaphore = DispatchSemaphore(value: 0) | |
let dataTask = self.dataTask(with: urlrequest) { | |
data = $0 | |
response = $1 | |
error = $2 | |
semaphore.signal() | |
} | |
dataTask.resume() | |
_ = semaphore.wait(timeout: .distantFuture) | |
return (data, response, error) | |
} | |
} | |
func sync_req() -> Void { | |
let url = URL(string: "http://example.com")! | |
var request = URLRequest(url: url) | |
request.httpMethod = "GET" | |
let (data, response, error) = URLSession.shared.synchronousDataTask(urlrequest: request) | |
if let error = error { | |
print("Synchronous task ended with error: \(error)") | |
} | |
else { | |
print("Synchronous task ended without errors.") | |
print("response: \(response)") | |
if let data = data, | |
let urlContent = NSString(data: data, encoding: String.Encoding.ascii.rawValue) { | |
print(urlContent) | |
} else { | |
print("Error: \(error)") | |
} | |
if let data = data, | |
let urlContent = NSString(data: data, encoding: String.Encoding.ascii.rawValue) { | |
print(urlContent) | |
} else { | |
print("Error: \(error)") | |
} | |
//print("data: \(data)") | |
} | |
} | |
sync_req() | |
async_req() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment