如何使用 Alamofire 4.0 获取 JSON 字典/数组并将其显示在 tableView Cell 上

Posted

技术标签:

【中文标题】如何使用 Alamofire 4.0 获取 JSON 字典/数组并将其显示在 tableView Cell 上【英文标题】:how to fetch JSON dictionary/array with Alamofire 4.0 and show it on tableView Cell 【发布时间】:2016-10-24 07:04:59 【问题描述】:

我正在尝试获取应用程序的 HomeFeed,因为这是我的第一个主要应用程序。我发现很难获取 JSON 数据并将其显示在我的 tableViewCell 上,尤其是转换 JSON Array/Dictionary 和使用它。 任何形式的帮助将不胜感激和救命!

这是我的HomeFeedTableView 课程:

class HomeFeedTableView: UIViewController 


@IBOutlet weak var menuButton: UIBarButtonItem!
@IBOutlet weak var cameraBtn: UIButton!
var tableView = UITableView()


var tableAuthor = [String]()
var tableTitle = [String]()

override func viewDidLoad() 
    super.viewDidLoad()

    //cameraBtn possition
    cameraBtn.layer.zPosition = 1000

    if self.revealViewController() != nil 
        menuButton.target = self.revealViewController()
        menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
        self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
    

    getJSON()



override func didReceiveMemoryWarning() 
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.



// Get JSON
func getJSON()

    let getEndPoint: String = "http://myURL/api/get_user_post/"
    Alamofire.request(getEndPoint)
        .responseJSON  response in

            guard response.result.error == nil else 
                // got an error in getting the data, need to handle it
                print("error calling GET")
                print(response.result.error!)
                return
            

            if let value =  response.result.value 

                let json = JSON(value)
                //print(json.description)

                for items in json.dictionary! 

                    //let author: String? = anItem["author"].stringValue
                    //let title: String? = anItem["title"].stringValue
                    //self.tableAuthor.append(author!)
                    //self.tableTitle.append(title!)

                    print(items)

                



                DispatchQueue.main.async 
                    self.tableView.reloadData()
                
            
    



// MARK: - Table view data source

 func numberOfSectionsInTableView(_ tableView: UITableView) -> Int 
    // #warning Incomplete implementation, return the number of sections
    return 1


 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    // #warning Incomplete implementation, return the number of rows
    return status.count



 func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell 
    // Configure the cell...

    let cell: HomeFeedTableViewCell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as! HomeFeedTableViewCell
    let img = UIImage(named: imageMain[(indexPath as NSIndexPath).row])
    cell.ImageMain.image = img
   // cell.statusMain.text = tableAuthor[indexPath.row]

    let proImg = UIImage(named: imageMain[(indexPath as NSIndexPath).row])
    cell.profileImage.image = proImg
    cell.profileImage.layer.cornerRadius = 20.00
    cell.profileImage.clipsToBounds = true

    cell.likeBtn.layer.borderWidth = 1.2
    cell.likeBtn.layer.borderColor = UIColor.gray.cgColor
    cell.likeBtn.layer.cornerRadius = 5
    cell.likeBtn.clipsToBounds = true

    cell.commentBtn.layer.borderWidth = 1.2
    cell.commentBtn.layer.borderColor = UIColor.gray.cgColor
    cell.commentBtn.layer.cornerRadius = 5
    cell.commentBtn.clipsToBounds = true

    return cell


@IBAction func cameraBtnClicked(_ sender: AnyObject) 
    print("Camera Clicked")



我得到了这个 JSON 响应

("main_content", [
 
   "author" : "maruf khandakar",
   "post_id" : 110,
   "post_date" : "October 3, 2016",
   "title" : "hjhjhjhjkljkhasfreiwutb cltjutjuregjre nb",
   "show_comment_number" : "0",
   "show_likes" : "0",
   "post_img" : [
  
   "guid" : "http:\/\/myURL\/wp-content\/uploads\/2016\/10\/IMG_1475492476.jpg"
      
],
 "author_img" : "http:\/\/myUrl\/wp-  content\/uploads\/2016\/10\/Screenshot_1-2.png",
   "post_time" : "11:01 am",
   "blog_text" : "sfdhjusolidasfjgfkdsjfdklshfj"
  ,
 
"author" : "maruf khandakar",
"post_id" : 112,
"post_date" : "October 3, 2016",
"title" : "hjhjhjhjkljkhasfreiwutb cltjutjuregjre nb0",
"show_comment_number" : "1",
"show_likes" : "1",
"post_img" : [
   
    "guid" : "http:\/\/myUrl\/wp-  content\/uploads\/2016\/10\/IMG_1475494067.jpg"
   
  ],
  "author_img" : "http:\/\/myURL\/wpcontent\/uploads\/2016\/10\/Screenshot_1-2.png",
  "post_time" : "11:27 am",
  "blog_text" : "sfdhjusolidasfjgfkdsjfdklshfj0"
 ,
 
  "author" : "russell99",
  "post_id" : 129,
  "post_date" : "October 24, 2016",
  "title" : "russels 1st post",
  "show_comment_number" : "0",
  "show_likes" : "0",
  "post_img" : [
    
      "guid" : "http:\/\/myURL\/wpcontent\/uploads\/2016\/10\/IMG_1477280037.jpg"
    
   ],
   "author_img" :    "http:\/\/muURL\/Content\/Images\/Products\/NoImageAvailable   .jpg",
   "post_time" : "3:33 am",
  "blog_text" : "russel post"
 ,
 
  "author" : "russell99",
  "post_id" : 131,
  "post_date" : "October 24, 2016",
  "title" : "russels 2nd post",
  "show_comment_number" : "0",
  "show_likes" : "0",
  "post_img" : [
    
      "guid" :    "http:\/\/myURL\/wpcontent\/uploads\/2016\/10\/IMG_1477282075.jpg"
    
   ],
  "author_img" :    "http:\/\/muURL\/Content\/Images\/Products\/NoImageAvailable  .jpg",
  "post_time" : "4:07 am",
  "blog_text" : "russel post 2"

])

因为我是 Alamofire 的新手,所以这让我很困惑。请帮忙。

【问题讨论】:

【参考方案1】:

您的 JSON 响应是 Array 类型,而不是 Dictionary 所以这样设置 for 循环。

for items in json.arrayValue 

    let author: String? = anItem["author"].stringValue
    let title: String? = anItem["title"].stringValue
    self.tableAuthor.append(author!)
    self.tableTitle.append(title!)

注意:您需要创建自定义类型的数组,例如[Book],而不是使用多个数组,首先您需要创建自定义类Book

【讨论】:

以上是关于如何使用 Alamofire 4.0 获取 JSON 字典/数组并将其显示在 tableView Cell 上的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Xcode 8.0 中安装 Alamofire 4.0

如何在 Alamofire 4.0 中仅使用参数和正文在 swift 中使用 POST 方法发送请求?

Alamofire 4.0 和 Swfit 3 的字典

api没有使用alamofire显示序列化的json输出

Alamofire 4.0:timeoutIntervalForRequest

如何在 Alamofire 4.0 中添加带有上传进度百分比的标签的进度条