gpt4 book ai didi

swift - 如何实例化映射类? ( swift - alamofireObjectMapper)

转载 作者:行者123 更新时间:2023-11-30 12:29:44 25 4
gpt4 key购买 nike

我有一个名为 Movie 的映射类,并且我发出了一个返回此类型的 API 请求。如何使用 API 响应的值实例化此类?

电影映射类:

class Movie: Mappable {

var posterURL : String?
var title : String?
var runtime : String?
var director : String?
var actors : String?
var genre : String?
var plot : String?
var production : String?
var released : String?
var year : String?
var imdbID : String?
var imdbRating : String?

required init?(map: Map) {

}

func mapping(map: Map) {
posterURL <- map["Poster"]
title <- map["Title"]
runtime <- map["Runtime"]
director <- map["Director"]
actors <- map["Actors"]
genre <- map["Genre"]
plot <- map["Plot"]
production <- map["Production"]
released <- map["Released"]
year <- map["Year"]
imdbID <- map["imdbID"]
imdbRating <- map["imdbRating"]
}
}

在我的 MovieViewController 中,我正在进行 API 调用并传递我的 socket 标签的值。但我想通过分配在我的 API 调用中获得的值来实例化此类。

func getMovieById() {

let requestURL = "https://www.omdbapi.com/?i=\(String(describing: imdbID!))"
print("URL: \(requestURL)")


Alamofire.request(requestURL).responseObject{ (response: DataResponse<Movie>) in
print("|MovieController| Response is: \(response)")

DispatchQueue.main.async {
let spinnerActivity = MBProgressHUD.showAdded(to: self.view, animated: true)
spinnerActivity.label.text = "Loading";
spinnerActivity.isUserInteractionEnabled = false;
}

let movie = response.result.value


if let posterURL = movie?.posterURL {
print("Poster URL: \(posterURL)")

let imgStg: String = posterURL
print("---> Image string: \(imgStg)")
let imgURL: URL? = URL(string: imgStg)
let imgSrc = ImageResource(downloadURL: imgURL!, cacheKey: imgStg)

self.movPosterImageView.layer.cornerRadius = self.movPosterImageView.frame.size.width/2
self.movPosterImageView.clipsToBounds = true

//image cache with KingFisher
self.movPosterImageView.kf.setImage(with: imgSrc)

}


if let title = movie?.title {
print("Title: \(title)")
self.movTitleLabel.text = title
}


if let runtime = movie?.runtime {
print("Runtime: \(runtime)")
self.movRuntimeLabel.text = runtime
}

if let genre = movie?.genre {
print("Genre: \(genre)")
self.movGenreLabel.text = genre
}

if let plot = movie?.plot {
print("Plot: \(plot)")
self.movPlotTextView.text = plot
}

if let rating = movie?.imdbRating {
print("Rating: \(rating)")
self.movRatingLabel.text = rating
}

if let director = movie?.director {
print("Director: \(director)")
self.movDirectorLabel.text = director
}

if let production = movie?.production {
print("Production: \(production)")
self.movProductionLabel.text = production
}

if let actors = movie?.actors {
print("Actors: \(actors)")
self.movActorsLabel.text = actors
}

if let released = movie?.released {
print("Released in: \(released)")
self.movReleasedLabel.text = released
}





DispatchQueue.main.async {
MBProgressHUD.hide(for: self.view, animated: true)
}

}//Alamofire.request

}//getMovieByID()

大概是这样的

let movieDetails: Movie = Movie(plot = movie?.plot, title = movie?.title, ...)

如何使用可映射类来做到这一点?

<小时/>

更新

我正在尝试组织这些东西,而且我还必须重用代码,所以这个内部函数对我来说似乎更好。因此,我开始将 API 调用分开,如下所示:

文件:OMDB.swift

import Foundation
import Alamofire
import AlamofireObjectMapper



func getMovieIdFromAPI(imdbID: String, completionHandler: @escaping (Movie) -> () ) {

let requestURL = "https://www.omdbapi.com/?i=\(imdbID)"

print("|getMovieIdFromAPI| URL: \(requestURL)")


Alamofire.request(requestURL).responseObject{ (response: DataResponse<Movie>) in
print("|Alamofire request| Response is: \(response)")

if let movieResult = response.result.value{
completionHandler(movieResult)
}
}
}

下一步,我尝试创建一个 MovieDAO,在这里我必须实例化我的对象,对吧?因此,在与我的 Movie 类相同的文件中,我创建了一个具有以下函数的 MovieDAO 类:

class MovieDAO {

func getMovieDetailed<Movie: Mappable>(imdbID: String, completionHandler: @escaping (Movie) -> ()) {

getMovieIdFromAPI(imdbID: imdbID, completionHandler: {
(movieResult) in

let mapper = Mapper<Movie>()
let movieDetailed = mapper.map(movieResult)!



completionHandler(movieDetailed)

})

}

}

但是我不太明白答案,xcode 给了我一个错误

   let movieDetailed = mapper.map(movieResult)!
^Error: Argument labels '(_:)' do not match any available overloads

您能否解释一下我如何使用本例中给出的答案?

最佳答案

ObjectMapper 可以帮助您获取模型类的实例,并根据您的 API 响应设置属性值。您需要执行最后一步,告诉 ObjectMapper 使用您提供的 json 执行“映射”过程。您可以使用此通用方法来解析任何可映射类的响应

static func parseModel<Model: Mappable>(modelResponse modelResponse: AnyObject, modelClass: Model.Type) ->  Model? {

let mapper = Mapper<Model>()
let modelObject = mapper.map(modelResponse)!

return modelObject
}

关于swift - 如何实例化映射类? ( swift - alamofireObjectMapper),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43714026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com