0

There are two requests being made. The first request returns an array of int. The objects in the array of int are unique. Meaning, it has a string value associated with an int. To get the value for the key, I have to make a second request. The second URL request has the value for the array of int from the first URL. (Second URL Request) I am trying to make a URL request using swift 3. Following is the code:

func fetchMovieGenres(_ forGenreIds: [Int], callback: @escaping (String) -> Void) {
    let params = [ API: APIKey ]
    var request = URLRequest(url: urlBuilder.tmdbURLBuilder(params as [String: Any], withPathExtension: MovieGenreList))
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = urlBuilder.session.dataTask(with: request) {(data, response, error) in
        do {
            if let data = data, let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any], let results = json["genre"] as? [[String:Any]] {
                callback(Genre.genreFromResults(results)) // Cannot convert value of type '[Genre]' to expected argument type 'String'
            }
        } catch {
            print("Error parsing JSON: \(error)")
        }
    }
    task.resume()
}

In the viewDidLoad() I am doing this: genreLabel.text = "\(fetchMovieGenres(result?.genreIds)!)"

What is happening is, I am trying to return an array of string from remote URL and populate that in UILabel. But for some reason, I am not being able to achieve that.

Dev-A-iOS
  • 5
  • 5

1 Answers1

1

First of all, you need to supply a callback for the eventual string. Assuming that Genre.genreFromResults(results) is your desired string for the label...

Change your method to:
private func fetchMovieGenres(_ forGenreIds: [Int], callback: (String) -> Void) {

Change:
self.genre = Genre.genreFromResults(results) print(json)
to:
callback(Genre.genreFromResults(results))

And change your method call to:

fetchMovieGenres(ids) { string in genreLabel.text = string }

IanSabine
  • 54
  • 5
  • Updated the question with refactored code and now I am getting `Cannot convert value of type '[Genre]' to expected argument type 'String'` – Dev-A-iOS Nov 16 '17 at 14:32
  • I don't know how you get whatever string you want from `Genre`. You'll need to write that bit yourself. If you can end up with `[String]`, you can concatenate them together with `stringArray.joined(separator: ", ")`. – IanSabine Nov 16 '17 at 19:57