无法将类型的值转换为预期的参数类型NSURLSessionDelegate

时间:2016-02-21 21:46:39

标签: ios swift types

我知道它应该很简单,但我是Swift的新手,不能在这里弄错:

public class API : NSObject, NSURLSessionDelegate{

    public class func sendHttpRequestNew(urlPath: String, params: AnyObject, method: String)-> Int {
        var delegate = self
        let txtUserName = "admin"
        let txtPassword = "test1234"
        let PasswordString = "\(txtUserName):\(txtPassword)"
        let PasswordData = PasswordString.dataUsingEncoding(NSUTF8StringEncoding)
        let base64EncodedCredential = PasswordData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
        let url: NSURL = NSURL(string: urlPath)!

        let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.HTTPMethod = method
        if method == "POST" || method == "PUT" {
            request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
        }
        let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("unique")
        let authString = "Basic \(base64EncodedCredential)"
        config.HTTPAdditionalHeaders = ["Authorization" : authString]
        let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)

        let downloadTask = session.downloadTaskWithRequest(request)
        downloadTask.resume()
    }
}

我在self的这一行收到错误: let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)

无法将'API.type'类型的值转换为预期的参数类型NSURLSessionDelegate

我做错了什么?

1 个答案:

答案 0 :(得分:9)

此处的问题是使用class声明方法,使其成为type method。当您在此方法中引用self时,您指的是类API本身,因此也就是错误。

public class API : NSObject, NSURLSessionDelegate

声明API是NSObject的子类,符合NSURLSessionDelegate。

将委托分配给URL会话时,分配的对象必须是API的 实例 。 有两种方法可以解决这个问题:

  1. 通过删除class前缀使sendHttpRequest()成为常规方法,或者,
  2. 使用let session = NSURLSession(configuration: config, delegate: API(), delegateQueue: nil)创建会话,该会话创建API实例并将其作为委托传递。
  3. 在我看来,第一种选择更好。这样你可以在其他地方保留一个API的实例,并像这样对你进行网络调用。