在Jift中将JSON数据解析为UIPickerView

时间:2016-07-10 16:51:38

标签: php json swift

我有一个代表国家的UIPickerview,我试图从MYSQL数据库中获取数据但我无法处理来自PHP文件的即将到来的数据。我找不到任何Swift解决方案,这就是为什么我在这里。

//its the default values of pickerview
var pickOption = ["one", "two", "three", "seven", "fifteen"]

func getCountries() {
    let url:NSURL = NSURL(string: "http:/domain.com/getCountriesLong.php")!
    let session = NSURLSession.sharedSession()

    let request = NSMutableURLRequest(URL: url)
    let task = session.downloadTaskWithRequest(request) {
        (
        let location, let response, let error) in

        guard let _:NSURL = location, let _:NSURLResponse = response  where error == nil else {
            print("error")
            return
        }

        let urlContents = try! NSString(contentsOfURL: location!, encoding: NSUTF8StringEncoding)

        guard let _:NSString = urlContents else {
            print("error")
            return
        }

        //all result is here
        //print(urlContents)
        //string to NSData conversion
        let data = urlContents.dataUsingEncoding(NSUTF8StringEncoding)
        do {
            //parse NSData to JSON
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)

            //pickOption = json["countryName"]
            //pickOption = json

        } catch {
            print("error serializing JSON: \(error)")
        }


    }

    task.resume()

}

这是PHP

$menuData = $db->get_results("SELECT countryName FROM countries ORDER BY countryName ASC");

echo json_encode($menuData);

我如何使用即将到来的数据作为我的UIPickerView的值?

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。而不是使用pickOption = json [" countryName"]我声明了新的数组。这是;

var arr = [String]()

    for name in json as! [AnyObject] {
         if let country = name["countryName"] as? String {
              arr.append(country)
         }
    }

self.pickOption = arr