swift - 如何从 NSURLSession.sharedSession().dataTaskWithRequest 获取数据

标签 swift nsurlsession

class PostFOrData {
    let url = NSURL( string: "http://210.61.209.194:8088/SmarttvWebServiceTopmsoApi/GetReadlist")
    var picUrl = NSURL(string : "http://210.61.209.194:8088/SmarttvMedia/img/epi00001.png")
    var responseString : NSString = ""

    func forData() -> NSString {

        let request = NSMutableURLRequest( URL: url!)
        request.HTTPMethod = "POST"
        var s : NSString = ""

        let postString : String = "uid=59"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

            if error != nil {
                println("error=\(error)")
                return
            } else {
                println("response = \(response!)")
                self.responseString = NSString(data: data, encoding: NSUTF8StringEncoding)!
                println("responseString = \(self.responseString)")
            }

        }

        // I want to return NSString here, but I always get nothing

        return self.responseString

    }
}

有人知道如何从任务中获取数据吗?

最佳答案

您无法直接从异步任务返回数据。

Swift 2 的解决方案是创建一个如下的完成处理程序:

class PostFOrData {
    // the completion closure signature is (NSString) -> ()
    func forData(completion: (NSString) -> ()) {
        if let url = NSURL(string: "http://210.61.209.194:8088/SmarttvWebServiceTopmsoApi/GetReadlist") {
            let request = NSMutableURLRequest( URL: url)
            request.HTTPMethod = "POST"
            let postString : String = "uid=59"
            request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
            let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                data, response, error in
                if let data = data,
                    jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
                    where error == nil {
                        completion(jsonString)
                } else {
                    print("error=\(error!.localizedDescription)")
                }
            }
            task.resume()
        }
    }
}


let pfd = PostFOrData()

// you call the method with a trailing closure
pfd.forData { jsonString in
    // and here you get the "returned" value from the asynchronous task
    print(jsonString)
}

这样,只有当异步任务完成时才会调用完成。这是一种“返回”数据的方法,而无需实际使用 return

Swift 3 版本

class PostFOrData {
    // the completion closure signature is (String) -> ()
    func forData(completion:  @escaping (String) -> ()) {
        if let url = URL(string: "http://210.61.209.194:8088/SmarttvWebServiceTopmsoApi/GetReadlist") {
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            let postString : String = "uid=59"
            request.httpBody = postString.data(using: String.Encoding.utf8)
            let task = URLSession.shared.dataTask(with: request) {
                data, response, error in
                if let data = data, let jsonString = String(data: data, encoding: String.Encoding.utf8), error == nil {
                    completion(jsonString)
                } else {
                    print("error=\(error!.localizedDescription)")
                }
            }
            task.resume()
        }
    }
}


let pfd = PostFOrData()

// you call the method with a trailing closure
pfd.forData { jsonString in
    // and here you get the "returned" value from the asynchronous task
    print(jsonString)
}

关于swift - 如何从 NSURLSession.sharedSession().dataTaskWithRequest 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38583565/

相关文章:

ios - 从 NSDictionary Issue 调用特定的数据键值

ios - 无法解码 JSON,因为缺少 Content-Type

ios - NSURLSession任务执行顺序

swift - 我的函数第一次总是返回 false

Swift 获取 URLSessionDataTask 开始时间/当前运行时间

ios - 在VC上快速拖动两个 View

swift - 时间标签未更新

ios - 在结构中获取与另一个关联的值的快捷方式

ios - 检测用户点击屏幕 Swift

ios - NSURLSession后台传输: Callback for each video downloaded from a queue