Reputation: 1590
I understand it should be very simple but I am a novice with Swift and cannot get what is wrong here:
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()
}
}
I got an error on this line with self
:
let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
Cannot convert value of type 'API.type' to expected argument type NSURLSessionDelegate
What am I doing wrong?
Upvotes: 4
Views: 7130
Reputation: 907
The issue here is the method is declared with class
, making it a type method
. When you refer to self
inside this method, you are referring to the class API
itself, and hence the error.
public class API : NSObject, NSURLSessionDelegate
is declaring API to be a subclass of NSObject, which conforms to NSURLSessionDelegate.
When assigning a delegate to the URL session, the object assigned has to be an instance of API. There are two ways to remedy this:
class
prefix, or,let session = NSURLSession(configuration: config, delegate: API(), delegateQueue: nil)
, which creates an instance of API and passes that as the delegate.In my opinion, the first option is better. That way you can keep an instance of API
around somewhere else and make your networking calls to it like that.
Upvotes: 13