有效的JSON在Swift 3中返回nil

时间:2016-08-06 11:33:40

标签: json swift binding null optional

我试图创建一个应用程序,将用户带到我的MySQL数据库中存储的街道地址。 JSON是有效的,我相信URL也是。

我相信正在发生的事情是数据丢失并通过可选绑定返回零。或者URL不正确(我确实在Playground中查看是否会返回nil并且URL没有&t;)

我一直在关注本教程: http://codewithchris.com/iphone-app-connect-to-mysql-database/ 这是我第一次将应用程序连接到数据库。

我相对较新,很快就试图掌握它。

有什么想法吗?任何帮助将不胜感激。提前谢谢。

我的服务器目前位于专用网络上。但我知道它不会影响API

数据下载但后来所有变量都是nil。 DetailViewController中的应用程序中断

的ViewController

 import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, HomeModelProtocal  {

//Properties

var feedItems: NSArray = NSArray()
var selectedLocation : LocationModel = LocationModel()
@IBOutlet weak var listTableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    //set delegates and initialize homeModel

    self.listTableView.delegate = self
    self.listTableView.dataSource = self

    let homeModel = HomeModel()
    homeModel.delegate = self
    homeModel.downloadItems()

}

func itemsDownloaded(items: NSArray) {

    feedItems = items
    self.listTableView.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: LocationModel = feedItems[indexPath.row] as!    LocationModel
    // Get references to labels of cell
    myCell.textLabel!.text = item.address

    return myCell
}

}

LocationModel

import Foundation

class LocationModel: NSObject {

//properties

var name: String?
var address: String?
var latitude: String?
var longitude: String?


//empty constructor

override init()
{

}

//construct with @name, @address, @latitude, and @longitude parameters

init(name: String, address: String, latitude: String, longitude: String) {

    self.name = name
    self.address = address
    self.latitude = latitude
    self.longitude = longitude

}


//prints object's current state

override var description: String {
    return "Name: \(name), Address: \(address), Latitude: \(latitude),   Longitude: \(longitude)"

}


}

HomeModel

 import Foundation

protocol HomeModelProtocal: class {
func itemsDownloaded(items: NSArray)
}


class HomeModel: NSObject, NSURLSessionDataDelegate {

//properties

weak var delegate: HomeModelProtocal!

var data : NSMutableData = NSMutableData()

let urlPath: String = "http://dev.devmelb.com/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")
        print(LocationModel())
        print(error)
        self.parseJSON()
    }
}

    func parseJSON() {

        var jsonResult: NSMutableArray = NSMutableArray()

        do{
            jsonResult = try      NSJSONSerialization.JSONObjectWithData(self.data, o .   ptions:NSJSONReadingOptions.AllowFragments) as! NSMutableArray

        } catch let error as NSError {
            print(error)

        }

        var jsonElement: NSDictionary = NSDictionary()
        let locations: NSMutableArray = NSMutableArray()

        for i in 0 ..< jsonResult.count
        {

            jsonElement = jsonResult[i] as! NSDictionary

            let location = LocationModel()
            print(location)

            //the following insures none of the JsonElement values are nil through optional binding
            if let name = jsonElement["Name"] as? String,
                let address = jsonElement["Address"] as? String,
                let latitude = jsonElement["Latitude"] as? String,
                let longitude = jsonElement["Longitude"] as? String

            {


                location.name = name
                location.address = address
                location.latitude = latitude
                location.longitude = longitude

            }

            locations.addObject(location)


        }

        dispatch_async(dispatch_get_main_queue(), { () -> Void in

            self.delegate.itemsDownloaded(locations)

        })


}
}

DetailViewController

import Foundation
import UIKit
import MapKit

class DetailViewController : UIViewController {

@IBOutlet weak var mapView: MKMapView!

var selectedLocation : LocationModel?

override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewDidAppear(animated: Bool) {
    // Create coordinates from location lat/long
    var poiCoodinates: CLLocationCoordinate2D = CLLocationCoordinate2D();

    print(selectedLocation)
    print("\(LocationModel())")
    poiCoodinates.longitude = CDouble(self.selectedLocation!.longitude!)!
    poiCoodinates.latitude = CDouble(self.selectedLocation!.latitude!)!
    // Zoom to region
    let viewRegion: MKCoordinateRegion = MKCoordinateRegionMakeWithDistance(poiCoodinates, 750, 750)
    self.mapView.setRegion(viewRegion, animated: true)
    // Plot pin
    let pin: MKPointAnnotation = MKPointAnnotation()
    pin.coordinate = poiCoodinates
    self.mapView.addAnnotation(pin)

    //add title to the pin
    pin.title = selectedLocation!.name



}

}

0 个答案:

没有答案