【问题标题】:Putting JSON data into an array when using Alamofire使用 Alamofire 时将 JSON 数据放入数组
【发布时间】:2017-07-19 10:22:33
【问题描述】:

我正在尝试从我的站点检索数据,我正在使用 Alamofire,如何将这些数据放入一个数组中,以便我可以使用它来填充我的表格视图?

   override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request("http://lytestech.ga/api/lytes/get_movies/").responseJSON { response in


            if let json = response.result.value {
                print("JSON: \(json)") // serialized json response
                let res = json as! NSDictionary
                let movies = res["movies"] as! NSArray
                // movieTitles = movies["movie_desc"]
                let movieTitles: [String] = movies["movietitile"] as! String
                print (movies)
                print (movieTitles)

            }


            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                print("Data: \(utf8Text)") // original server data as UTF8 string
            }
        }

    }

json 数据

JSON: {
    movies =     (
                {
            id = 66;
            "movie_desc" = "spiders bite";
            movietitile = spiderman;
        },
                {
            id = 64;
            "movie_desc" = horror;
            movietitile = mummy;
        }
    );
    status = ok;
}
(
        {
        id = 66;
        "movie_desc" = "spiders bite";
        movietitile = spiderman;
    },
        {
        id = 64;
        "movie_desc" = horror;
        movietitile = mummy;
    }
)

【问题讨论】:

  • 您可以为此使用 SwiftyJSON:github.com/SwiftyJSON/SwiftyJSON
  • 你知道如何从数组中填充表格视图吗?
  • 是的,我知道怎么做@raki
  • 然后创建一个数组类型的实例变量,将电影数据存储到该数组中,并将该数组传递给 tableview 的数据源方法以填充它。 @GideonLytes

标签: ios json swift alamofire


【解决方案1】:

将电影存储在电影NSArray

var movies = NSArray()

之后在cellForRowAt方法中你可以像这样显示数据。

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
        {
            let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier") as! YouCustomCell

            let movieDetail = movies[indexPath.row] as! NSDictionary

            cell.lblMovieName.text = movieDetail.value(forKey: "movietitile") as? String
            return cell
        }

注意:- 这只是代码框架,您可以根据您的自定义单元格和 Outlets 使用

【讨论】:

    【解决方案2】:
     var movies:[Dictionary<String,AnyObject>] = [] // Makes movies array global
     movies = res["movies"] // and tableview reload
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifier = "cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier) ??
            UITableViewCell(style: .default, reuseIdentifier: identifier)
    
        cell.textLabel!.text = movies[indexPath.row]["movietitile"] as? String
    
        return cell
    }
    

    【讨论】:

      【解决方案3】:

      func demo()
      {
          let str  : String =  "http://lytestech.ga/api/lytes/get_movies/"
          let url =  NSURL(string:str)
          let request = NSMutableURLRequest(URL: url!)
          request.HTTPMethod = "POST"
          request.setValue("application/json", forHTTPHeaderField: "Content-Type")
          Alamofire.request(request)
              .responseString { response in
                  switch (response.result) {
                  case .Success(let JSON):
                      let data = JSON.dataUsingEncoding(NSUTF8StringEncoding)!
                      do {
                          let responseString = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
                          // print(responseString!)
                          self.movieName = []
                          self.desc = []
                          let arr = responseString!["movies"] as! NSArray
                          for j in 0..<arr.count{
                              let dic = arr[j] as! NSMutableDictionary
                              self.movieName.addObject(dic.valueForKey("movietitile")!)
                              self.desc.addObject(dic.valueForKey("movie_desc")!)
                          }
                          self.removeIndicator()
                          self.contactTable.reloadData()
                      } catch _ as NSError {
                          //print(error)
                      }
                      break
                  case .Failure:
                      print("FAILURE")
                      self.removeIndicator()
                      break
                  }
          }
      }
      

      【讨论】:

        【解决方案4】:

        将您的回复 Data 转换为 Dictionary

        let dictionary: Dictionary? = NSKeyedUnarchiver.unarchiveObject(with: response.data) as! [String : Any]
        

        Dictionary中提取你的Array,有键名movies

         if let arryMovies1 = dictionary["movies"] as? [[String:Any]] {
        
                print (arryMovies1);
        
          // Now your have your Array 
          // You can Populate into UItableView
          // when your array is modified than you have to reload the tableData
        
        
               self.arryMovies=arryMovies1
              self.tableView.reloadData()
        
              }
        

        在您的cellForRowAtIndexPath 中用于填充列表视图

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
             {
                        let cell = tableView.dequeueReusableCell(withIdentifier: "you_cell_identifre") as! UITableCell
        
                        let dicMovie = self.arryMovies[indexPath.row] as! NSDictionary
        
                        cell.lableTitle.text = dicMovie.value(forKey: "movietitile") as? String
        
                     return cell
                 }
        

        希望对你有帮助

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多