简体   繁体   中英

Error: “Type '*' does not conform to protocol '*'” using custom class and NSURLSession

I know there are many questions and answers for this does not conform to protocol error, but nothing matched and/or worked for my specific problem.

I really don't know, what I'm doing wrong. I wanted to divide my code into classes so i can separate my "backend" from my "frontend" (ViewController.swift).

In this case, I want a class which handles the API call in the background, so i created a ApiController.swift file with the following code:

import Foundation


protocol OMDbApiControllerProtocol {
    func didReceiveOMDbResults(results: Dictionary<String, String>)
}

class OMDbApiController {

    var delegate: OMDbApiControllerProtocol?

    init(delegate: OMDbControllerProtocol?) {
        self.delegate = delegate
    }

    func searchOMDb(forSeries: String, season: String, episode: String) {

        let term = forSeries.stringByReplacingOccurrencesOfString(" ", withString: "+", options: .CaseInsensitiveSearch, range: nil)
        if let escapedTerm = term.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {

            let url = NSURL(string: "http://www.omdbapi.com/?s=\(escapedTerm)")
            println(url!)
            let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: {
                (data, response, error) in

                var jsonResults = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as? Dictionary<String, String>

                dispatch_async(dispatch_get_main_queue()) {
                   self.delegate?.didReceiveOMDbResults(jsonResults!)
                }

            })
            task.resume()
        }
    }

}

Then I "imported" the protocol in the ViewController.swift file:

class SeriesInfoViewController: UIViewController, UIScrollViewDelegate, OMDbApiControllerProtocol

This creates the error: Type 'SeriesInfoViewController' does not conform to protocol 'OMDbApiControllerProtocol'

I hope you understand my problem and please considerate, that this is my first asked question on Stack Overflow.

I think you kind of misunderstood how your protocol should be used. By 'importing' the protocol you are saying that your class actually conforms to that protocol. In this case that would mean that SeriesInfoViewController has to implement didReceiveOMDbResults in order to actually conform to the protocol.

So if you implement that method you should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM