在表格视图单元格中通过 alamofire 解析 json 数据
Posted
技术标签:
【中文标题】在表格视图单元格中通过 alamofire 解析 json 数据【英文标题】:Parsing json data through alamofire in table view cells 【发布时间】:2017-08-14 09:01:44 【问题描述】:我正在尝试解析我的表格视图单元格中的 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")
【问题讨论】:
除了 pretending 是常量的私有支持变量的问题在 Swift 中是荒谬的。只需使用let
关键字。
@keshu Rai 是在表函数中调用吗?那时您是否有数据存在于数组中?使用断点并调试您的代码。
实际上没有 .. 值没有存储在数组中 .. 我在 viewdid 加载中调用了数组上的打印函数,它显示了一个空错误 .. 你能检查一下代码吗?知道我在犯什么错误。请帮我很大的忙,因为我被困在这段代码中很长时间了。
downloadPostData() 你在哪里调用函数????我在 viewdidLoad 中找不到。
【参考方案1】:
问题很可能是因为您尝试解析键 posts
的值两次,一次在 PostData
中,一次在 ViewController
中。
首先,在 Swift 3 中,JSON 字典是 [String:Any]
,其次——正如我在评论中已经提到的——私有后备变量在 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 ?? ""
【讨论】:
老兄,这很有帮助.. 现在我正在我的单元格中获取数据,非常感谢......但我没有得到我在视图中传递的图像。在我的 PostDataTableViewCell 代码中的 configureCell() 函数中。有什么解决方案吗? 基本上同步加载数据是不好的。您应该在模型中添加图像属性并使用缓存系统。在您的代码中,当用户滚动时,图像会一次又一次地重新加载。并且不要对字符串使用字符串插值"\()"
。这是多余的。
实际上 m 只是一个新人 .. m 在学习阶段 .. wud 肯定会改进我的代码 :) 谢谢以上是关于在表格视图单元格中通过 alamofire 解析 json 数据的主要内容,如果未能解决你的问题,请参考以下文章