dongxing9219 2016-07-10 16:51
浏览 60

在Jift中将JSON数据解析为UIPickerView

I have a UIPickerview which represents countries and i am trying to get its data from MYSQL database but i couldnt handle the coming data from PHP file. I couldnt find any Swift solution so thats why i am here.

//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()

}

Here is the PHP

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

echo json_encode($menuData);

How can i use coming data as value of my UIPickerView ?

  • 写回答

1条回答 默认 最新

  • duanmei1885 2016-07-10 17:52
    关注

    I found the solution. instead of using pickOption = json["countryName"] i have declared new array. Here it is;

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

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致