Skip to content

Instantly share code, notes, and snippets.

@hotpaw2
Created May 6, 2017 22:07
Show Gist options
  • Select an option

  • Save hotpaw2/827a6e710d24036bdcb6a37aab921c6a to your computer and use it in GitHub Desktop.

Select an option

Save hotpaw2/827a6e710d24036bdcb6a37aab921c6a to your computer and use it in GitHub Desktop.

Revisions

  1. hotpaw2 created this gist May 6, 2017.
    64 changes: 64 additions & 0 deletions nsurl.dtask.test1.swift
    Original 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