试图让HTTP获取请求在swift上工作

时间:2015-09-15 01:29:50

标签: ios xcode swift request

我对swift相对较新。至于现在,我需要在我的应用程序中向table view显示mysql数据。我已经准备了json数据,看起来像

[{"restaurantnames":"restaurant 1","type":"type 1","location":"location 1"},{"restaurantnames":"restaurant 2","type":"type 1","location":"location 1"}]

现在我需要阅读json响应并在应用启动时使用这些数据填充我的表格视图。目前,我已使用静态数据填充了table rows。我正在尝试将this模块用于GET请求。这是我的RestaurantViewController.swift

override func viewDidLoad() {
        super.viewDidLoad()

        let url = NSURL(string: "http://localhost:8888/restaurant/registeruser.php")

        let request = NSMutableURLRequest(URL: url!)

        request.HTTPMethod = "GET"

        request.timeoutInterval = 60

        NSURLSession.sharedSession().dataTaskWithURL(request, completionHandler: { (data:NSData!, respone:NSURLResponse!, error:NSError!) -> Void in
            dispatch_async(dispatch_get_main_queue()){

            var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil!) as? NSDictionary


            }



        })        

    }

1 个答案:

答案 0 :(得分:1)

enter image description here

class ViewController: UIViewController  {     

    var restName:Array< String > = Array < String >()
    var restType:Array< String > = Array < String >()

    override func viewDidAppear(animated: Bool) {
         get_data_from_url("http://localhost:8888/restaurant/registeruser.php")
     }

   func numberOfSectionsInTableView(tableView: UITableView) -> Int {
       return 1
    }


   func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return restName.count
   }

   func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

       let cellIdentifier = "CategoryTableViewCell"
       let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CategoryTableViewCell

       cell.categoryName.text = restName[indexPath.row]
       cell.Name.text = restType[indexPath.row]

       return cell
   }


   func get_data_from_url(url:String) {


      var url:NSURL = NSURL(string: url)!

      var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
      request.HTTPMethod = "GET"
      request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
      request.setValue("*/*", forHTTPHeaderField: "Accept")


      var reponseError: NSError?
      var response: NSURLResponse?

      var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)


       if  urlData != nil && reponseError == nil {

        let res = response as! NSHTTPURLResponse!;

        //NSLog("Response code: %ld", res.statusCode);

        if (res.statusCode >= 200 && res.statusCode < 300) {

            var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

            //NSLog("Response ==> %@", responseData);

            extract_json(urlData!)


        } else {
            var alertView:UIAlertView = UIAlertView()
            alertView.title = "Sign in Failed!"
            alertView.message = "Connection Failed"
            alertView.delegate = self
            alertView.addButtonWithTitle("OK")
            alertView.show()
        }


    } else {
        var alertView:UIAlertView = UIAlertView()
        alertView.title = "Sign in Failed!"
        alertView.message = "Connection Failure"
        if let error = reponseError {
            alertView.message = (error.localizedDescription)
        }
        alertView.delegate = self
        alertView.addButtonWithTitle("OK")
        alertView.show()
    }



}

 func extract_json(data:NSData) {

    var error: NSError?

    let jsonData: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers , error: &error)

    if (error == nil) {
        if let rest_cat_list = jsonData as? NSArray
        {
            for (var i = 0; i < rest_cat_list.count ; i++ )
            {
                if let rest_obj = rest_cat_list[i] as? NSDictionary
                {
                    if let restaurant = rest_obj["restaurantnames"] as? String
                    {
                       restName.append(restaurant)

                        if let restType = rest_obj["type"] as? String
                        {
                           restType.append(restType)
                        }
                    }
                }
            }

        }
     }
      do_table_refresh();
   }

 func do_table_refresh() {

    dispatch_async(dispatch_get_main_queue(), {
        self.tableView.reloadData()
        return
    })
  }
}

首先访问此网站并验证您的网址

然后根据您的设置替换以下给定值: -

      request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
      request.setValue("*/*", forHTTPHeaderField: "Accept")