1
我的理解應該是很簡單的,但我與斯威夫特新手並不能得到什麼是錯在這裏:無法將類型的價值預期參數類型NSURLSessionDelegate
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
我在做什麼錯?
如果我使用第一個選項,當我調用函數時,我不能將參數傳遞給此函數,因爲調用應該如下所示:'API.sendHttpRequestNew(self:API)' – Roberto
您需要通過執行類似的操作來創建API對象'let api = API()',然後調用'api'對象的方法:api.sendHttpRequestNew(...) – caughtinflux
感謝您的回答! – Roberto