我在使用NSURLSession检测数据接收时遇到问题。使用NSURLConnection的等效代码确实有效,但这里没有包含。
在此示例中,我正在向google.com提出请求。 completionHandler工作完成"完成"打印(如果您更改代码,也会打印数据等。)
然而,didReceiveData未被触发且接收到数据"从未打印过。
我已经浏览了文档,并进行了大量的搜索,我认为这看起来是正确的,但我似乎无法让它发挥作用。绝对会感谢任何帮助。
(我需要使用didReceiveData,因为我要解析流式json api。)
谢谢!
import UIKit
class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionDataDelegate, NSURLSessionTaskDelegate {
override func viewDidAppear(animated: Bool) {
let session = NSURLSession.sharedSession()
var task = session.dataTaskWithURL(NSURL(string: "https://google.com")!, completionHandler: { (data, response, error) -> Void in
print("complete")
})
task.resume()
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
print("received data")
}
}
答案 0 :(得分:2)
有两个问题。
创建会话时,您必须定义委托。这就是没有调用didReceiveData的主要原因。
第二个问题是,如果使用completionHandler块,则会绕过所有委托函数。在NSURlSession的代码中,它说
extension NSURLSession {
/*
* data task convenience methods. These methods create tasks that
* bypass the normal delegate calls for response and data delivery,
* and provide a simple cancelable asynchronous interface to receiving
* data. Errors will be returned in the NSURLErrorDomain,
* see <Foundation/NSURLError.h>. The delegate, if any, will still be
* called for authentication challenges.
*/
您必须实现检查完成,错误等所需的每个委托功能。
更新后的代码如下:
import UIKit
class ViewController: UIViewController, NSURLSessionDelegate {
override func viewDidAppear(animated: Bool) {
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
var task = session.dataTaskWithURL(NSURL(string: "https://google.com")!)
task.resume()
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
print("received data")
}
}
答案 1 :(得分:-3)
您只能在CREATE TRIGGER catchHim BEFORE INSERT ON myTable
FOR EACH ROW
BEGIN
IF EXISTS(SELECT * FROM myTable WHERE userID=NEW.userID) THEN
INSERT INTO history (key,userID,action,note,date) VALUES (NEW.myColumn1, NEW.myColumnForUserId, .....);
END IF;
END;
中获取数据。为什么要使用completionHandler
?
下面的代码将向您展示如何获取收到的数据
didReceiveData