简体   繁体   English

解析JSON-在初始化之前使用“变量'jsonObject'

[英]Parsing JSON - "Variable 'jsonObject' used before being initialized

I am having a problem with a JSON library I am using for an iOS 9.0 project, on Xcode 7 beta 5, running on OS X El Cap. 我在运行于OS X El Cap的Xcode 7 beta 5上的iOS 9.0项目中使用的JSON库存在问题。

I followed this link to make a part of my app that involved some basic MapKit functionality. 点击此链接 ,使我的应用程序包含了一些基本的MapKit功能。 In this "part", I have to parse JSON data into "issue locations" (it's an app for a school newspaper, and we're going to have a map of all locations where they drop off issues). 在此“部分”中,我必须将JSON数据解析为“问题位置”(这是一份学校报纸的应用程序,我们将获得所有问题发生地点的地图)。

Here is my problem (I don't understand it, as I am a beginner iOS developer). 这是我的问题(因为我是iOS初学者,所以我不理解)。 I get an error on the following line, that says "Variable 'jsonObject' used before being initialized". 我在下一行收到错误消息,提示“初始化前使用了变量'jsonObject'”。

The line in question is the third "paragraph" in the "loadInitialData" function. 该行是“ loadInitialData”函数中的第三个“段落”。

if let jsonObject = jsonObject as? [String: AnyObject],

And here is all of my code for the "MapViewController.swift" file governing everything that happens in my MapKit view. 这是“ MapViewController.swift”文件的所有代码,用于管理MapKit视图中发生的所有事情。

import UIKit
import MapKit
import CoreLocation

class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

// Map View outlet declaration
@IBOutlet weak var mapView: MKMapView!

// Hamburger button declaration
@IBOutlet weak var menuButton:UIBarButtonItem!

var locationManager: CLLocationManager?

// Creating a variable to hold the "IssueLocation" objects from the JSON file
var issueLocations = [IssueLocation]()

override func viewDidLoad() {
    super.viewDidLoad()

    // Hamburger button configuration
if self.revealViewController() != nil {
    menuButton.target = self.revealViewController()
    menuButton.action = "revealToggle:"
    self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
    }

    // Setting the Map type to standard
    mapView.mapType = MKMapType.Standard

    // Configuring locationManager and mapView delegate
    locationManager = CLLocationManager()
    mapView.delegate = self

    // Set the center of campus as the first location, before we show the actual user location
    let initialLocation = CLLocation(latitude: 44.226397, longitude: -76.495571)
    let regionRadius: CLLocationDistance = 1000

    // Centering map on center of campus
    func centerMapOnLocation(location: CLLocation) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 2.0, regionRadius * 2.0)
        mapView.setRegion(coordinateRegion, animated: true)
    }

    loadInitialData()
    mapView.addAnnotations(issueLocations)

    // Show user location and start updating user location
    mapView.showsUserLocation = true
    locationManager?.startUpdatingLocation()

//        // Show a sample issue location on the Map
//        let IssueLocation = IssueLocation(locationName: "Stirling Hall, West  Entrance", coordinate: CLLocationCoordinate2D(latitude: 44.22468034747186, longitude: -76.49805217981339))
//        
//        mapView.addAnnotation(IssueLocation)

    // Do any additional setup after loading the view.
}

func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
    mapView.centerCoordinate = userLocation.location!.coordinate
}

func loadInitialData() {

    let fileName = NSBundle.mainBundle().pathForResource("IssueLocations", ofType: "json");
    var readError : NSError?
    var data: NSData?

    do {
        data = try NSData(contentsOfFile: fileName!, options: NSDataReadingOptions(rawValue: 0))
    } catch _ {
        data = nil
    }

    var error: NSError?
    let jsonObject: AnyObject!
    if let data = data {

        do {
            jsonObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
        } catch _ {
            jsonObject = nil
        }

    }

    if let jsonObject = jsonObject as? [String: AnyObject],
        let jsonData = JSONValue.fromObject(jsonObject)?["data"]?.array {
            for issueLocationJSON in jsonData {
                let issueLocation = IssueLocation.fromJSON(issueLocationJSON.array!)
                        issueLocations.append(issueLocation)



            }

    }
}

// Checking location authorization status and requesting permission from user if status is not ".AuthorizedWhenInUse"
func checkLocationAuthorizationStatus() {

    if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
        mapView.showsUserLocation = true
     } else {
        locationManager?.requestWhenInUseAuthorization()
        }
    }

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    checkLocationAuthorizationStatus()
    }

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


/*
// 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.
}
*/


}

If if let data = data evaluates to false , then jsonObject will not be initialized since all the initialization for that object happens inside that if statement. 如果if let data = data计算结果为false ,则不会初始化jsonObject因为该对象的所有初始化都在if语句内进行。 Try initializing jsonObject to nil when you create the variable. 创建变量时,尝试将jsonObject初始化为nil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM