如何修改现有函数以将数据返回到变量

时间:2019-04-13 15:03:37

标签: ios swift

我正在编码一个视图控制器,该控制器获取最新发行电影的JSON数组并将其显示在类中。我有其余的代码与静态对象一起工作,但是我是处理json数据并从函数返回它的新手。下面是我的工作函数,我需要将数据返回到其他函数可以访问的变量。 非常感谢任何帮助

func latestMovieReleases()
    {
        URLSession.shared.dataTask(with: latestReleasesURL!) {(data, response, error) in
        do
            {
                let movies = try JSONDecoder().decode([latestReleasesJSON].self, from: data!)

                for movie in movies
                {
                    print(movie.title)
                }
            }
            catch
            {
                print("We Got An Error :- ")
                print(error)
            }
        }.resume()
    }

这是位于我的结构文件中的结构

struct latestReleasesJSON: Decodable
{
    let id: String
    let title: String
    let posterurl: String
    let year: String
    let releaseDate: String
}

1 个答案:

答案 0 :(得分:0)

您可以尝试

func latestMovieReleases(completion:@escaping([latestReleasesJSON]? -> ()))
{
    URLSession.shared.dataTask(with: latestReleasesURL!) {(data, response, error) in

      guard let data = data else {completion(nil) ; return } 
      do
        {
            let movies = try JSONDecoder().decode([latestReleasesJSON].self, from: data)

            for movie in movies
            {
                print(movie.title)
            }

            completion(movies)
        }
        catch
        {
            print("We Got An Error :- ")
            print(error)
            completion(nil)
        }
    }.resume()
}

致电

 latestMovieReleases { (res) in
    if let re = res {
      print(re)
    }
 }

struct latestReleasesJSON: Decodable {
  let id,title,posterurl,year,releaseDate: String 
}