我不明白为什么我的代码不起作用.这里是:
class Test: NSURLSessionDataDelegate { func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if(error == nil) { print("Hallo") } else { print(error?.userInfo) } } func createRequest() { let dictionary = [ "mailAddress":"foo@example.com", ..... ] let nsData: NSData? do { nsData = try NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions(rawValue:0)) } catch _ { nsData = nil } let defaultConfigObject = NSURLSessionConfiguration.defaultSessionConfiguration() let defaultSession = NSURLSession(configuration: defaultConfigObject, delegate: self, delegateQueue: NSOperationQueue.mainQueue()) let url = NSURL(string: "http:...")! let urlRequest = NSMutableURLRequest(URL: url) urlRequest.HTTPMethod = "POST" urlRequest.HTTPBody = nsData urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") let dataTask = defaultSession.dataTaskWithRequest(urlRequest) dataTask.resume() } }
而错误:
类型测试不符合协议'NSObjectProtocol'.
有任何想法吗?
如果你跟进继承链,NSURLSessionDataDelegate
继承NSURLSessionTaskDelegate
,继承NSURLSessionDelegate
,继承,NSObjectProtocol
.该协议具有所需的各种方法,比如isEqual(_:)
和respondsToSelector(_:)
你类未实现.
通常你在这里做的是使你的类继承NSObject
符合NSObjectProtocol
:
class Test: NSObject, NSURLSessionDataDelegate { ... }