URLSession 之map-reduce操作

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
func debug(_ t:Any?...,  function:String = #function, line:Int = #line,  file:String = #file) {
    print(t,(file as NSString).lastPathComponent, function, line, "in Thread", Thread.current, separator: "\t",  terminator: "\n")
}
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let urlArray = ["https://www.baidu.com","https://www.baidu.com","https://www.baidu.com","https://www.baidu.com"]
let r = urlArray.map { (url) -> String in
    let url = URL(string: url)!
    var str:String?
    let group = DispatchGroup()
    group.enter()
    let task = session.dataTask(with: url, completionHandler: {(data:Data?, r:URLResponse?, err:Error?) -> Void in
        if let data = data {
            str =  String(data: data, encoding: String.Encoding.utf8)
        }
        group.leave()
    })
    task.resume()
    group.wait()
    return str ?? "no data"
    }.reduce("", +)
print("result", r)

你可能感兴趣的:(URLSession 之map-reduce操作)