【发布时间】:2016-11-08 11:21:42
【问题描述】:
我有一个项目正在尝试使用 alamofire 从 web url 引入数据。我正在尝试引入图像和文本,但不断构建失败。我正在尝试将数据(图像和文本)添加到标签 = 1 和 2。我的代码低于任何帮助将不胜感激。我对斯威夫特相当陌生。谢谢
SWIFT
import UIKit
import Alamofire
struct postinput {
let mainImage : UIImage!
let name : String!
}
class TableViewController: UITableViewController {
var postsinput = [postinput]()
var mainURL = "https://www.testJSON.com"
typealias JSONstandard = [String : AnyObject]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
callAlamo(url: mainURL)
}
func callAlamo(url : String){
Alamofire.request(url).responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)
})
}
func parseData(JSONData : Data) {
do {
var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONstandard
if let posts = readableJSON["posts"] as? [JSONstandard] {
for post in posts {
let title = post["title"] as! String
if let images = post["image"] as? JSONstandard {
let mainImageURL = URL(string: imageData["url"] as! String)
let mainImageData = NSData(contentsOf: mainImageURL!)
let mainImage = UIImage(data: mainImageData as! Data)
}
postsinput.append(postinput.init(mainImage: mainImage, name: name))
}
self.tableView.reloadData()
}
}
catch {
print(error)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postsinput.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
// cell?.textLabel?.text = titles[indexPath.row]
let mainImageView = cell?.viewWithTag(2) as! UIImageView
mainImageView.image = postsinput[indexPath.row].mainImage
let mainLabel = cell?.viewWithTag(1) as! UILabel
mainLabel.text = postsinput[indexPath.row].name
return cell!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
JSON
{ posts: [ { id: “000000”, url: "/content/interview2”, date: "2016-11-03 09:01:41", modified: "2016-11-03 09:03:47", title: "An interview", image: "https://www.example.com/sites/default/files/oregood.jpeg", summary: { value: "<p>Latin text here</p> ", format: "filtered_html" } ]}
【问题讨论】:
-
你的
parseData函数中的imageData和name是什么? -
构建失败在哪里?
-
在你的
func parseData(JSONData : Data)中 -
你得到的构建失败错误是什么?
-
我正在学习教程,所以 imageData 和名称可能与我的 JSON 结构不对应,这就是我感到困惑的原因。