Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
错误-带Alamofire和AlamoFireObject映射器(swift-iOS)的Resquest函数_Ios_Json_Swift_Runtime Error_Alamofire - Fatal编程技术网

错误-带Alamofire和AlamoFireObject映射器(swift-iOS)的Resquest函数

错误-带Alamofire和AlamoFireObject映射器(swift-iOS)的Resquest函数,ios,json,swift,runtime-error,alamofire,Ios,Json,Swift,Runtime Error,Alamofire,首先,我是一个初学者,我正在尝试构建一个应用程序,在OMDB API上搜索一部电影,并返回一个电影列表(当按标题搜索时),当按imdbID搜索时,返回一个特定的电影。我必须对api提出两种类型的请求,因为“按id搜索”的结果与“按标题搜索”的结果具有相同的属性,但具有更多细节(需要此属性才能显示包含此结果列表中选定电影的视图) 因此,我(这里)建议使用AlamoFileObjectMapper/ObjectMapper来做得更好。我是这样做的: import Foundation import

首先,我是一个初学者,我正在尝试构建一个应用程序,在OMDB API上搜索一部电影,并返回一个电影列表(当按标题搜索时),当按imdbID搜索时,返回一个特定的电影。我必须对api提出两种类型的请求,因为“按id搜索”的结果与“按标题搜索”的结果具有相同的属性,但具有更多细节(需要此属性才能显示包含此结果列表中选定电影的视图)

因此,我(这里)建议使用AlamoFileObjectMapper/ObjectMapper来做得更好。我是这样做的:

import Foundation
import AlamofireObjectMapper

class SearchResponse: Mappable {
    var isSuccess  : String?
    var searchArray: [Movie]?
    var searchCount: String?

    required init?(map: Map) {
    }

    func mapping(map: Map) {
        isSuccess   <- map["Response"]
        searchArray <- map["Search"]
        searchCount <- map["totalResults"]
    }
}

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 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"]
        year       <- map["Year"]
        imdbID     <- map["imdbID"]
        imdbRating <- map["imdbRating"]
   }
}
//Get movie by title - the user will enter the title on a searchbar

let url = "https:www.omdbapi.com/?s=\(imdbTitle)"

func getMoviesByTitle (imdbTitle: String) {
    /* The Alamofire function using ObjectMapper goes here */
    switch
    case .success():
        /*Something*/
        completionHandler(???)
    case .failure():
       /*Something*/
        completionHandler(???)
}


//Get movie by ID

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

func getMovieByID(imdbID: String) {
    /* The Alamofire function using ObjectMapper goes here */
    if let response {
       completioHandler(???)
    } /* Something like this? */
}
我需要一些向导。当我按标题搜索电影时,它返回一个JSON,其中包含响应、搜索(“电影数组”)和totalResults。在本例中,我的电影类只有四个映射属性(Poster、Title、Year、imdbID)

  • 这个映射正确吗
  • 我如何才能为每个案例提出这些请求?我是说,我该还什么?(因为我的getMovie函数需要一个completionHandler,对吗?)
  • 编辑 因此,我在我的SearchTableViewController上尝试了以下方法:

    import UIKit
    import Alamofire
    import AlamofireObjectMapper
    import ObjectMapper
    import Kingfisher
    
    
    
    class SearchTableViewController: UITableViewController, UISearchResultsUpdating {
    
    
    @IBOutlet var searchTableView: UITableView!
    
    @IBAction func showResults(_ sender: Any) {
        let searchController = UISearchController(searchResultsController: nil)
        self.present(searchController, animated: true, completion: nil)
        searchController.searchBar.barTintColor = self.searchTableView.backgroundColor!
        searchController.searchResultsUpdater = self
    
    }
    
    
    var movies = [Movie]()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        searchTableView.dataSource = self
        searchTableView.delegate = self
    
    }
    
    func updateSearchResults(for searchController: UISearchController) {
    
        if let searchText = searchController.searchBar.text {
    
            if searchText == "" {
                return
            }
    
            else {
                let movieSearched: String = searchText.replacingOccurrences(of: " ", with: "_")
    
    
                    // MARK: Alamofire Get by Title
    
                    let URL = "https://www.omdbapi.com/?s=\(movieSearched)&type=movie"
    
    
                    Alamofire.request(URL).responseObject{ (response: DataResponse<SearchResponse>) in
    
                        print("response is: \(response)")
    
                        switch response.result {
    
                        case .success(let value):
                            let searchResponse = value
                            self.movies = (searchResponse.searchArray)!
                            self.searchTableView.reloadData()
    
                        case .failure(let error):
                            let alert = UIAlertController(title: "Error", message: "Error 4xx / 5xx: \(error)", preferredStyle: UIAlertControllerStyle.alert)
                            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
                            self.present(alert, animated: true, completion: nil)
                        }
    
                    }
    
    
    
                    DispatchQueue.main.async {
                        let spinnerActivity = MBProgressHUD.showAdded(to: self.view, animated: true)
                        spinnerActivity.label.text = "Loading";
                        spinnerActivity.detailsLabel.text = "Searching movie..."
                        spinnerActivity.isUserInteractionEnabled = false;
                    }
    
    
    
    
                    DispatchQueue.main.async {
                        MBProgressHUD.hide(for: self.view, animated: true)
                    }
    
    
    
            }
    
        }
    }
    
    
    // MARK: - Table view data source
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return movies.count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SearchCellIdentifier", for: indexPath) as! SearchTableViewCell
    
        let movie = movies[indexPath.row]
    
        let imgStg: String = movie.posterURL!
        let imgURL: URL? = URL(string: imgStg)
        let imgSrc = ImageResource(downloadURL: imgURL!, cacheKey: imgStg)
    
        cell.titleLabel.text = movie.title
        cell.yearLabel.text = movie.year
    
    
        cell.posterImageView.layer.cornerRadius = cell.posterImageView.frame.size.width/2
        cell.posterImageView.clipsToBounds = true
    
        //image cache with KingFisher
        cell.posterImageView.kf.setImage(with: imgSrc)
    
    
    
        return cell
    }
    
    
    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */
    
    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */
    
    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
    
    }
    */
    
    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */
    
    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    
    }
    
    导入UIKit
    进口阿拉莫菲尔
    导入AlamoFileObject映射器
    导入对象映射器
    进口翠鸟
    类SearchTableViewController:UITableViewController、UISearchResultsUpdated{
    @IBVAR searchTableView:UITableView!
    @iAction func showResults(\发送方:任意){
    设searchController=UISearchController(searchResultsController:nil)
    self.present(searchController,动画:true,完成:nil)
    searchController.searchBar.barTintColor=self.searchTableView.backgroundColor!
    searchController.SearchResultsUpdate=self
    }
    var movies=[Movie]()
    重写func viewDidLoad(){
    super.viewDidLoad()
    searchTableView.dataSource=self
    searchTableView.delegate=self
    }
    func updateSearchResults(对于searchController:UISearchController){
    如果让searchText=searchController.searchBar.text{
    如果searchText==“”{
    回来
    }
    否则{
    let moviesearch:String=searchText.replacingOccurrences(of:,with:“”)
    //马克:阿拉莫菲尔按头衔获得
    让URL=”https://www.omdbapi.com/?s=\(movieSearched)&类型=电影“
    中的Alamofire.request(URL).responseObject{(响应:DataResponse)
    打印(“响应为:\(响应)”)
    开关响应。结果{
    成功案例(let value):
    让searchResponse=value
    self.movies=(searchResponse.searchArray)!
    self.searchTableView.reloadData()
    案例。失败(let错误):
    让alert=UIAlertController(标题:“错误”,消息:“错误4xx/5xx:\(错误)”,首选样式:UIAlertControllerStyle.alert)
    addAction(UIAlertAction(标题:“确定”,样式:UIAlertActionStyle.default,处理程序:nil))
    self.present(警报、动画:true、完成:nil)
    }
    }
    DispatchQueue.main.async{
    让spinnerActivity=MBProgressHUD.showAdded(到:self.view,动画:true)
    spinnerActivity.label.text=“加载”;
    SpinerActivity.detailsLabel.text=“搜索电影…”
    spinneActivity.isUserInteractionEnabled=false;
    }
    DispatchQueue.main.async{
    MBProgressHUD.hide(用于:self.view,动画:true)
    }
    }
    }
    }
    //标记:-表视图数据源
    重写func numberOfSections(在tableView:UITableView中)->Int{
    //#警告未完成执行,返回节数
    返回1
    }
    重写func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int{
    //#警告未完成实现,返回行数
    返回电影。计数
    }
    重写func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell{
    让cell=tableView.dequeueReusableCell(带有标识符:“SearchCellIdentifier”,for:indexath)作为!SearchTableViewCell
    let movie=movies[indexPath.row]
    让imgStg:String=movie.posterURL!
    让imgURL:URL?=URL(字符串:imgStg)
    让imgSrc=ImageResource(下载URL:imgURL!,cacheKey:imgStg)
    cell.titleLabel.text=movie.title
    cell.yearLabel.text=movie.year
    cell.posterImageView.layer.cornerRadius=cell.posterImageView.frame.size.width/2
    cell.posterImageView.clipsToBounds=true
    //基于翠鸟的图像缓存
    cell.posterImageView.kf.setImage(带:imgSrc)
    返回单元
    }
    /*
    //替代以支持表视图的条件编辑。
    重写func tableView(tableView:UITableView,canEditRowAt indexath:indexPath)->Bool{
    //如果不希望指定的项可编辑,则返回false。
    返回真值
    }
    */
    /*
    //替代以支持编辑表格视图。
    重写func tableView(tableView:UITableView,commit editingStyle:UITableViewCellEditingStyle,forRowAt indexPath:indexPath){
    如果editingStyle==.delete{
    //从数据源中删除该行
    tableView.deleteRows(位于:[indexPath],带:.fade)
    }如果editingStyle==,则为else。插入{
    //创建相应类的新实例,将其插入数组,并向表视图添加新行
    }    
    }
    */
    /*
    //替代以支持重新排列表视图。
    重写func tableView(tableView:UITableView,moveRowAt fromIndexPath:IndexPath,to:IndexPath){
    }
    */
    /*
    //重写以支持表视图的条件重新排列。
    重写func tableView(tableView:UITableView,canMoveRowAt indexath:indexPath)->Bool{
    //如果不希望该项目可重新订购,则返回false。
    返回真值
    }
    */
    /*
    //标记:-导航
    //在基于故事板的应用程序中,您通常需要做一些公关工作
    
    var movies:[Movie]?
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let safeMovies = movies {
            return safeMovies.count
        } else {
            return 0 //no movies were returned.  you could eventually show an error here
        }
    }
    
    case .success(let value):
        let searchResponse = value
        self.movies = searchResponse.searchArray
        self.searchTableView.reloadData()
    
    func updateSearchResults(for searchController: UISearchController) {
    
        guard let searchText = searchController.searchBar.text, searchText != "" else {
            return
        }
    
        let movieSearched: String = searchText.replacingOccurrences(of: " ", with: "_")
        // MARK: Alamofire Get by Title
        let URL = "https://www.omdbapi.com/?s=\(movieSearched)&type=movie"
        Alamofire.request(URL).responseObject{ (response: DataResponse<SearchResponse>) in
            print("response is: \(response)")
            DispatchQueue.main.async {
                MBProgressHUD.hide(for: self.view, animated: true)
            }
            switch response.result {
            case .success(let value):
                let searchResponse = value
                self.movies = (searchResponse.searchArray)!
                self.searchTableView.reloadData()
    
            case .failure(let error):
                let alert = UIAlertController(title: "Error", message: "Error 4xx / 5xx: \(error)", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }
        }
    
        DispatchQueue.main.async {
            let spinnerActivity = MBProgressHUD.showAdded(to: self.view, animated: true)
            spinnerActivity.label.text = "Loading";
            spinnerActivity.detailsLabel.text = "Searching movie..."
            spinnerActivity.isUserInteractionEnabled = false;
        }
    }