Consume data Json - Webservice Swift 2 - iOS

2

I need to check price in buscape api (returns in json) in my app with swift 2. Could someone help me do this or point out a tutorial on how to do it?

How to use buscape api: Using the BuscaPé API to obtain a list of products using the Find Product List

Test link: link

    
asked by anonymous 19.01.2016 / 01:28

2 answers

3

You can use NSURLSession dataTaskWithURL and create a method to download the data asynchronously as follows:

func searchBuscape(query: String) {
    guard
        let escapedSearch = query.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()),
        url = NSURL(string:  "http://sandbox.buscape.com.br/service/findProductList/554163674d2f57624d676f3d/BR/?categoryId=77&keyword=\(escapedSearch)&format=json")
    else { return }
    NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
        guard
            let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
            let data = data where error == nil
        else { return }
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            var error: NSError?
            let json = JSON(data: data, options: .AllowFragments, error: &error)
            if let error = error {
                print(error.localizedDescription)
            }

            print("===json start")
            print(json)
            print("===json end")

            print(json["totalresultsreturned"])  // 16
            print(json["product"][0]["product"]["pricemin"])  // 819.90
            print(json["product"][0]["product"]["pricemax"])  // 1199.00

            // pra voce extrair um array de dicionários do json object você precisa acessar arrayObject property da segunte forma
            if let products = json["product"].arrayObject as? [[String:AnyObject]] {
                for product in products {
                    print("productStart=======")
                    print(product)
                    print("productEnd=======")
                }
                let pricesArrayMin = products.map{$0["product"]?["pricemin"]??.doubleValue ?? 0}.sort()
                print("pricesMinStart=======")
                print(pricesArrayMin)
                print(pricesArrayMin.count)    // 16
                print(pricesArrayMin.first!)   // 539.1    (produto mais barato)
                print(pricesArrayMin.last!)    // 2898.99
                print("pricesMinEnd=======")
            }
        }
    }).resume()
}

Do not forget to edit the info.plist to add to the App Transport Security Settings the search-foot domain or use https. You will also need to add the SwiftyJSON.swift file to your project.

    
19.01.2016 / 21:35
5

You can use the Alamofire library to make your requests, it is the most stable and built up swift 2.0, others such as AFNetworking are not so encouraged by still being made in Objective-C.

To add to your project manually you can view one of these videos: Alamofire - Youtube.

Or simply follow the tutorial in the github documentation.

A tip to be able to manage these libraries / components that you need to install in your project and Cocoapods , it is a dependency manager, such as php composer.

On the same site you will find an installation tutorial for it, and how to include the libraries.

Once you add Alamofire to your project, you just have to make a request like this:

 let url = "http://sandbox.buscape.com/service/findProductList/564771466d477a4458664d3d/?keyword=samsung"
Alamofire.request(.GET, url)
  .responseJSON {
    response in
      print(response.request) // original URL request
    print(response.response) // URL response
    print(response.data) // server data
    print(response.result) // result of response serialization

    if let JSON = response.result.value {
      print("JSON: \(JSON)")
    }
    
19.01.2016 / 02:23