简体   繁体   English

试图使HTTP get请求迅速工作

[英]trying to make HTTP get request work on swift

I am relatively new to swift . 我是比较新的swift As for now, I need to display the mysql datas to table view in my app. 到目前为止,我需要在应用程序中显示mysql数据以table view显示。 I have already prepared by json data which looks like 我已经准备了看起来像的json数据

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

Now I need to read json response and and populate my table view with these datas on app launch. 现在,我需要阅读json响应,并在应用启动时使用这些数据填充表格视图。 For now, I have populated my table rows with the static data. 现在,我已经用静态数据填充了table rows I am trying to make use of this module for the GET request. 我正在尝试将此模块用于GET请求。 This my RestaurantViewController.swift 这是我的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


            }



        })        

    }

在此处输入图片说明

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
    })
  }
}

First go to this site and validate your URL 首先访问此站点并验证您的URL

then replace below given values according to your settings :- 然后根据您的设置替换以下给定值:-

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

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

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