내 코드에서 선택적 바인딩을 사용하려고했지만 잘못된 메서드를 사용했는지 궁금해서 디버깅 및 실행시 nil로 표시됩니다. 여기 json 요소가 0이 아닌 것을 어떻게 보장 할 수 있습니까?
Here is the code which shows me trying to parse my JSON
내가 시도하고 내 JSON을 구문 분석하는 데 사용하는 코드입니다 : 마지막으로import Foundation
class PropertyModel: NSObject {
//properties
var propertyType: String?
var price: String?
var distance: String?
//empty constructor
override init()
{
}
//construct with @propertyType, @price and @distance parameters
init(propertyType: String, price: String, distance: String) {
self.propertyType = propertyType
self.price = price
self.distance = distance
}
//prints object's current state
override var description: String {
return "Property Type: \(propertyType), Price: \(price), Distance: \(distance)"
}
}
를 실행 한 다음, 여기에
import Foundation
protocol ListingModelProtocol: class {
func itemsDownloaded(items: NSArray)
}
class ListingModel: NSObject, NSURLSessionDataDelegate {
weak var delegate: ListingModelProtocol!
var data : NSMutableData = NSMutableData()
let urlPath: String = "http://booksmart.hol.es/service.php" // this will be changed to the path where service.php lives
func downloadItems() {
let url: NSURL = NSURL(string: urlPath)!
var session: NSURLSession!
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithURL(url)
task.resume()
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
self.data.appendData(data);
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if error != nil {
print("Failed to download data")
}else {
print("Data downloaded")
self.parseJSON()
}
}
func parseJSON() {
var jsonResult: NSMutableArray = NSMutableArray()
do{
jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray
} catch let error as NSError {
print(error)
}
var jsonElement: NSDictionary = NSDictionary()
let properties: NSMutableArray = NSMutableArray()
for(var i = 0; i < jsonResult.count; i+=1)
{
jsonElement = jsonResult[i] as! NSDictionary
let property = PropertyModel()
//the following insures none of the JsonElement values are nil through optional binding
if let propertyType = jsonElement["Property Type"] as? String,
let price = jsonElement["Price"] as? String,
let distance = jsonElement["Distance"] as? String
{
property.propertyType = propertyType
property.price = price
property.distance = distance
}
properties.addObject(property)
}
dispatch_async(dispatch_get_main_queue(), {() -> Void in
self.delegate.itemsDownloaded(properties)
})
}
}
내가 내 데이터베이스에서 데이터를 다운로드하는 데 사용하는 코드입니다 다음은 이것을 신속하게 표 셀에 넣으려고 시도하는 코드입니다.
import UIKit
class First_ResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, ListingModelProtocol {
//Properties
var feedItems: NSArray = NSArray()
var selectedProperties : PropertyModel = PropertyModel()
@IBOutlet weak var PropertyListTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//set delegates and initialize homeModel
self.PropertyListTableView.delegate = self
self.PropertyListTableView.dataSource = self
let listingModel = ListingModel()
listingModel.delegate = self
listingModel.downloadItems()
// Do any additional setup after loading the view.
}
func itemsDownloaded(items: NSArray) {
feedItems = items
self.PropertyListTableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of feed items
return feedItems.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Retrieve cell
let cellIdentifier: String = "BasicCell"
let myCell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier)!
// Get the location to be shown
let item: PropertyModel = feedItems[indexPath.row] as! PropertyModel
// Get references to labels of cell
myCell.textLabel!.text = item.propertyType
return myCell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
여기를 보셨습니까? http://stackoverflow.com/a/28129484/1585677 –
이미지가 아닌 텍스트로 코드를 게시하십시오. – pedrouan