Created
May 6, 2017 22:07
-
-
Save hotpaw2/827a6e710d24036bdcb6a37aab921c6a to your computer and use it in GitHub Desktop.
Revisions
-
hotpaw2 created this gist
May 6, 2017 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,64 @@ // // command-line Swift test of an NSURLSession dataTask // 2017-May-06 [email protected] (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