Sid
Sid

Reputation: 5833

making HTTP GET Request with swift

I am trying to make get request with swift and populate my table view. As of now, I have prepared my json data that needs to be filled in my table which looks like enter image description here

As I have just started to learn swift, I am finding a bit confusing to make a request. Here is my RestaurantTableViewController.swift

override func viewDidLoad() {
        super.viewDidLoad()

        var url: String = "http://localhost:8888/restaurant/registeruser.php"

        var request: NSMutableURLRequest = NSMutableURLRequest()

        request.URL = NSURL(string: url)

        request.HTTPMethod = "GET"

        request.timeoutInterval = 60


        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (respose:NSURLResponse!, data:NSData!, error:NSError!) -> Void in

            var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil

            let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

            if (jsonResult != nil){
                //success
                println(jsonResult)

                let dataArray = jsonResult["name"] as! NSArray;

                for item in dataArray {  //loop through data items

                    let obj = item as! NSDictionary

                    for(key, value) in obj{

                        let allnames = obj["name"] as! NSString;
                    }
                }
            }
        }

    }

This is all I have done up to now, after this, how should I get my table filled with restaurant name, type, and location. Any thorough help will be much appreciated.

Upvotes: 0

Views: 1301

Answers (2)

The Developer
The Developer

Reputation: 21

The best code is the following I use it every time I do a request hope it helps you!

   let url = URL(string: "https://google.com")
    let task = URLSession.shared.dataTask(with: ((url ?? URL(string: "https://google.com"))!)) { [self] (data, response, error) in
        
        do {
            let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: [])
            print(jsonResponse)
            guard let newValue = jsonResponse as? [String:Any] else {
                print("invalid format")
                }
            }

        
        catch let error {
            print("Error: \(error)")
        }
        
    task.resume()
}

Upvotes: 0

Nick Hayward
Nick Hayward

Reputation: 178

I would suggest using https://github.com/daltoniam/JSONJoy-Swift it'll make things a lot easier and cleaner.

As for the call

var DISPATCH_TIME_FOREVER: UInt64 { get }

var url: String = "http://localhost:8888/restaurant/registeruser.php"
let sem = dispatch_semaphore_create(0)

var responseData = NSData()
NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {(data, response, error) -> Void in
        responseData = data
        dispatch_semaphore_signal(sem)
    }).resume()
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER)
    let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

        if (jsonResult != nil){
            //success
            println(jsonResult)

            let dataArray = jsonResult["name"] as! NSArray;

            for item in dataArray {  //loop through data items

                let obj = item as! NSDictionary

                for(key, value) in obj{

                    let allnames = obj["name"] as! NSString;
                }
            }
        }

Upvotes: 1

Related Questions