从post方法中返回json数据并追加到数组

时间:2016-06-28 00:42:39

标签: json swift post

我尝试从帖子方法网址中检索数据,这是我的代码

    let url = NSURL(string:"http://urlwithpostmethod.com")

    let data = NSData(contentsOfURL: url!)

    values = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray





    for dataObject : AnyObject in values
    {
        if let data = dataObject as? NSDictionary
        {

            self.ids.append(data["id"] as! Int)
            self.titles.append(data["name_en"] as! String)
            self.descs.append(data["discription_en"] as! String)
            self.images.append(data["image"] as! String)









        }
    }

但是当我运行应用程序崩溃时:(并没有从网址中检索数据并获得错误

  

致命错误:在解包可选值时意外发现nil

有关如何从POST方法URL检索数据的任何建议吗?

这是我的json从url返回

[
  {
    "id": 8,
    "name_ar": "زيوت التروس",
    "name_en": "Gear Oils",
    "discription_ar": "GEAR OILS - BEST FOR EXTENDING GEARS LIFETIME",
    "discription_en": "GEAR OILS - BEST FOR EXTENDING GEARS LIFETIME",
    "image": "uploads/category/1466952382_3ed3d-gear_oils.png",
    "sort": 0,
    "status": 1,
    "parent_id": 0,
    "created_at": "2016-06-26 14:16:39",
    "updated_at": "2016-06-26 14:46:22"
  },
  {
    "id": 12,
    "name_ar": "Passenger Vehicles Motor Oil",
    "name_en": "Passenger Vehicles Motor Oil",
    "discription_ar": "PASSENGER VEHICLES MOTOR OIL - EXCELLENT PERFORMANCE FOR YOUR PASSENGER VEHICLE",
    "discription_en": "PASSENGER VEHICLES MOTOR OIL - EXCELLENT PERFORMANCE FOR YOUR PASSENGER VEHICLE",
    "image": "uploads/category/1466952496_6b90d-passenger_vehicles.png",
    "sort": 0,
    "status": 1,
    "parent_id": 0,
    "created_at": "2016-06-26 14:48:16",
    "updated_at": "2016-06-26 14:48:16"
  },
  {
    "id": 13,
    "name_ar": "Industrial Lubricants",
    "name_en": "Industrial Lubricants",
    "discription_ar": "INDUSTRIAL LUBRICANTS - EXCELLENT PERFORMANCE FOR SPECIFIC TECHNICAL APPLICATIONS",
    "discription_en": "INDUSTRIAL LUBRICANTS - EXCELLENT PERFORMANCE FOR SPECIFIC TECHNICAL APPLICATIONS",
    "image": "uploads/category/1466952588_c554d-pro.png",
    "sort": 0,
    "status": 1,
    "parent_id": 0,
    "created_at": "2016-06-26 14:49:48",
    "updated_at": "2016-06-26 14:49:48"
  },
  {
    "id": 18,
    "name_ar": "Coolant water",
    "name_en": "Coolant water",
    "discription_ar": "Test",
    "discription_en": "Test",
    "image": "uploads/category/1466973030_image.png",
    "sort": 0,
    "status": 1,
    "parent_id": 0,
    "created_at": "2016-06-26 20:30:30",
    "updated_at": "2016-06-26 20:30:30"
  }
]

2 个答案:

答案 0 :(得分:0)

post方法文件中的URL是否附加了任何内容?例如,像:

local URL = "http://www.location_of_json.com/json.php?userid="..mime.b64(userid).."&password="..mime.b64(password);

也许数据没有被发送到json文件?

答案 1 :(得分:0)

一般情况下,尽量避免使用强制解包as!,尤其是在解析后端数据时。这是让您的应用崩溃的有保证的方法。 相反,客户将这些值视为选项,有条件地解包并分别处理数据。