ios - 在 TableView 单元格中通过alamofire解析json数据

标签 ios json swift alamofire

我正在尝试解析 TableView 单元格中的 json 数据,但它不解析也不显示单元格。我附上了我的所有代码,请告诉我我犯了什么错误。我没有收到任何错误,但单元格没有显示。我为 json 解析创建了单独的类和函数并将其存储在数组中。

//
//  ViewController.swift
//  WorkingFeed2
//
//  Created by keshu rai on 08/08/17.
//  Copyright © 2017 keshu rai. All rights reserved.
//

import UIKit
import Alamofire
import MediaPlayer

class ViewController: UIViewController , UITableViewDelegate , UITableViewDataSource{

var post : PostData!
var posts = [PostData]()
typealias DownloadComplete = () -> ()

var arrayOfPostData : [String] = []
@IBOutlet weak var feedTable: UITableView!
override func viewDidLoad() {
    super.viewDidLoad()

    feedTable.dataSource = self
    feedTable.delegate = self


}

 func downloadPostData(completed: @escaping DownloadComplete) {
    Alamofire.request("https://new.example.com/api/posts/get_all_posts").responseJSON { response in
    let result = response.result
    if let dict = result.value as? Dictionary<String,AnyObject> {

        if let successcode = dict["STATUS_CODE"] as? Int {
            if successcode == 1 {
                if let postsArray = dict["posts"] as? [Dictionary<String,AnyObject>]
                {
               for obj in postsArray
                {
                        let post = PostData(postDict: obj)
                        self.posts.append(post)
                        print(obj)
                    }
//                        self.posts.remove(at: 0)
                    self.feedTable.reloadData()
                }
            }
        }
    }
    }
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 419
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell : ImageTableViewCell = self.feedTable.dequeueReusableCell(withIdentifier: "contentViewReuse") as! ImageTableViewCell
    let post = posts[indexPath.row]
    print(post)
    cell.configureCell(post : post)
    return cell


}
}

这是我的 PostData 类。

import Foundation

 class PostData {
var _profileImageURL : String?
var _fullName : String?
var _location : String?
var _title : String?
var _postTime : String?
var _likes : Int?
var _comments : Int?
var _mediaType : String?
var _contentURL : String?
var _content : String?
var _plocation : String?

var profileImageURL : String
{
    if _profileImageURL == nil {
        _profileImageURL = ""
    }
    return _profileImageURL!
}

var fullName : String
{
    if _fullName == nil {
        _fullName = ""
    }
    return _fullName!
}
var location : String {
    if _location == nil {
        _location = ""
    }
    return _location!
}
var title : String {
    if _title == nil {
        _title = ""
    }
    return _title!
}

var postTime : String {
    if _postTime == nil {
        _postTime = ""
    }
    return _postTime!
}

var likes : Int {
    if _likes == nil {
        _likes = 0
    }
    return _likes!
}

var comments : Int {
    if _comments == nil {
        _comments = 0
    }
    return _comments!
}

var mediaType : String {
    if _mediaType == nil {
        _mediaType = ""
    }
    return _mediaType!
}

var contentURL : String {
    if _contentURL == nil {
        _contentURL = ""
    }
    return _contentURL!
}
var content : String {
    if _content == nil {
        _content = ""
    }
    return _content!
}
var pLocation : String {
    if _plocation == nil {
        _plocation = ""
    }
    return _plocation!
}






init(postDict : Dictionary<String , AnyObject>)
{
    if let postsArray = postDict["posts"] as? [Dictionary<String,AnyObject>]
    {
        for i in 1..<postsArray.count
        {

            let fullName1 = postsArray[i]["full_name"] as? String
            self._fullName = fullName1


            let profileImageURL1 = postsArray[i]["profile_pic"] as? String
            self._profileImageURL = profileImageURL1

            let location1 = postsArray[i]["user_city"] as? String
            self._location = location1

            let title1 = postsArray[i]["title"] as? String
            self._title = title1

            let postTime1 = postsArray[i]["order_by_date"] as? String
            self._postTime = postTime1

            let likes1 = postsArray[i]["liked_count"] as? Int
            self._likes = likes1

            let comments1 = postsArray[i]["comment_count"] as? Int
            self._comments = comments1

            let mediaType1 = postsArray[i]["media_path"] as? String
            self._mediaType = mediaType1

            let contentURL1 = postsArray[i]["media_path"] as? String
            self._contentURL = contentURL1

            let content1 = postsArray[i]["content"] as? String
            self._content = content1

            let plocation1 = postsArray[i]["location"] as? String
            self._plocation = plocation1
        }
    }
}
}

这是我的 PostDataTableViewCell 代码。

import UIKit
import Alamofire

class PostDataTableViewCell: UITableViewCell {



@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var titlePost: UILabel!
@IBOutlet weak var profileFullName: UILabel!
@IBOutlet weak var profileUserLocation: UILabel!
@IBOutlet weak var likeBtn: UIButton!
var buttonAction: ( () -> Void) = {}


var pressed = false
@IBAction func likeBtnPressed(_ sender: Any) {
    if !pressed {
        let image = UIImage(named: "Like-1.png") as UIImage!
        likeBtn.setImage(image, for: .normal)
        pressed = true
    } else {

        let image = UIImage(named: "liked.png") as UIImage!
        likeBtn.transform = CGAffineTransform(scaleX: 0.15, y: 0.15)

        UIView.animate(withDuration: 2.0,
                       delay: 0,
                       usingSpringWithDamping: 0.2,
                       initialSpringVelocity: 6.0,
                       options: .allowUserInteraction,
                       animations: { [weak self] in
                        self?.likeBtn.transform = .identity
            },
                       completion: nil)
        likeBtn.setImage(image, for: .normal)
        pressed = false
    }


}
@IBAction func commentBtnPressed(_ sender: Any) {
    print("Commented")

}
@IBAction func shareBtnPressed(_ sender: Any) {
    self.buttonAction()


}
@IBAction func readContentBtnPressed(_ sender: Any) {
    print("Read")

}

@IBOutlet weak var contentPostLabel: UILabel!

@IBOutlet weak var contentTypeView: UIView!
@IBOutlet weak var likeAndCommentView: UIView!
@IBOutlet weak var numberOfLikes: UILabel!
@IBOutlet weak var numberOfComments: UILabel!
@IBOutlet weak var postLocation: UILabel!
@IBOutlet weak var postTimeOutlet: UILabel!


func configureCell(post : PostData)
{
    titlePost.text = "\(post.title)"
    profileFullName.text = "\(post.fullName)"
    profileUserLocation.text = "\(post.location)"
    numberOfLikes.text = "\(post.likes) Likes"
    numberOfComments.text = "\(post.comments) Comments"
    postLocation.text = "\(post.pLocation)"
    postTimeOutlet.text = "\(post.postTime)"
        let url = URL(string: post.profileImageURL)
        let data = try? Data(contentsOf: url!)
    profileImage.image = UIImage(data: data!)
    contentPostLabel.text = "\(post.content)"

    if post.mediaType == "image"
    {
    let url1 = URL(string: post.contentURL)
    let data1 = try? Data(contentsOf: url1!)
    let image = UIImage(data: data1!)
    let imageToView = UIImageView(image: image!)
    imageToView.frame = CGRect(x: 0, y: 0, width: 375  , height: 250)
    imageToView.contentMode = UIViewContentMode.scaleToFill
    contentTypeView.addSubview(imageToView)


    }
    else if post.mediaType == "null"
    {
        print("Status")
    }
    else if post.mediaType == "video"
    {
      print("Video")
    }
    else if post.mediaType == "youtube"
    {
     print("youtube")
    }
}

}

最佳答案

最有可能出现此问题的原因是您尝试解析关键 posts 的值两次,一次在 PostData 中,一次在 >ViewController.

首先,在 Swift 3 中,JSON 字典是 [String:Any],其次 - 正如我在评论中已经提到的 - 私有(private)支持变量在 Swift 中是无意义的。

PostData可以简化为

class PostData {
    let profileImageURL : String
    let fullName : String
    let location : String
    let title : String
    let postTime : String
    let likes : Int
    let comments : Int
    let mediaType : String
    let contentURL : String
    let content : String
    let plocation : String


    init(postDict : [String:Any])
    {           
        fullName = postDict["full_name"] as? String ?? ""
        profileImageURL = postDict["profile_pic"] as? String ?? ""
        location = postDict["user_city"] as? String ?? ""
        title = postDict["title"] as? String ?? ""
        postTime = postDict["order_by_date"] as? String ?? ""
        likes = postDict["liked_count"] as? Int ?? 0
        comments = postDict["comment_count"] as? Int ?? 0
        mediaType = postDict["media_path"] as? String ?? ""
        contentURL = postDict["media_path"] as? String ?? ""
        content = postDict["content"] as? String ?? ""
        plocation = postDict["location"] as? String ?? ""
    }
}

关于ios - 在 TableView 单元格中通过alamofire解析json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45670931/

相关文章:

ios - 当我第一次点击搜索栏时键盘会自动关闭

swift - AdMob 实现(只有代码,没有主要 Storyboard)

ios - 每次结果后清除 SFSpeechAudioBufferRecognitionRequest 的输入(Swift3)

ios - index 0 beyond bounds for empty array' *** First throw call stack :

ios - 使用对象对 NSArray 进行排序

ios - 在多个ios设备之间共享应用程序订阅中的非续订

Javascript:将值列表转换为对象集

json - 在 Golang 中解码任意 JSON

javascript - 使用函数向 JS 对象文字添加属性

ios - fatal error :Can't open realm