Skip to content

Instantly share code, notes, and snippets.

@hotpaw2
Created May 6, 2017 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hotpaw2/827a6e710d24036bdcb6a37aab921c6a to your computer and use it in GitHub Desktop.
Save hotpaw2/827a6e710d24036bdcb6a37aab921c6a to your computer and use it in GitHub Desktop.
test of command-line Swift for an NSURLSession dataTask
//
// command-line Swift test of an NSURLSession dataTask
// 2017-May-06 rhn@nicholson.com (hotpaw)
//
// compile and run using:
//
// swiftc nsurl.dtask.test1.swift -o mytest1
// ./mytest1
//
import Foundation
let urlstring = "http://www.hotpaw.com/rhn/hotpaw/"
var shouldKeepRunning = true
var sum = 0
class Delegate : NSObject, URLSessionDataDelegate
{
func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive data: Data)
{
let s = String(data: data, encoding: .utf8 ) ?? ""
let n = s.characters.count
sum += n
print("got data \(n), total = \(sum) ");
}
func urlSession(_ session: URLSession,
task: URLSessionTask,
didCompleteWithError error: Error?) {
if (error != nil) {
print(
"Download error: \(error!.localizedDescription)")
}
DispatchQueue.main.async {
shouldKeepRunning = false
print("url completion handler called")
}
}
}
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config,
delegate: Delegate(),
delegateQueue: nil )
guard let url = URL( string: urlstring ) else {
fatalError("Could not create URL object")
}
print("start")
session.dataTask( with: url ).resume()
let runLoop = RunLoop.current
while ( shouldKeepRunning
&& runLoop.run(mode: .defaultRunLoopMode,
before: .distantFuture ) ) {
}
print("end")
// eof
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment