Consume Json Data - Webservice Swift 2 - iOS

Asked

Viewed 1,964 times

2

  • What is your doubt? What have you tried to do? It is in sending requests or understanding in the article ?

  • @Gabrielrodrigues my doubt is how to use the data... Like a function where I pass the url and can call to pull the data... Got it ?

  • You already know how to make a request in Swift ?

  • @Gabrielrodrigues then , we will say that no... How would do?

  • You know how to use Cocoapods ? You’ve heard of it ?

  • @Gabrielrodrigues do not know... I’ve heard ... but would prefer without framework... But if you n suber without it can be with him...

Show 1 more comment

2 answers

5

You can use the library Alembic to carry out your requisitions, she and the most stable and built up Swift 2.0, others as Afnetworking are not so encouraged to still be made in Objetive-C.

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

Or simply follow the tutorial in the github documentation.

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

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

After you’ve added the Alamofire to your project just 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)")
    }
  • I’ll try it tomorrow...

  • Gabriel I’m having trouble installing the alembic manually and error me mac while installing the cocoapods... Is there any other way to install ?

  • @Augustofurlan that I know or manually or with cocoapods, what mistake are you having in the installation ? has a series of videos to do the installation in response.

  • it worked to install the cocoapods... However now d that can not find the arqivo plist... I do not know the reason... The file exists, because I found it in Finder...

3


You can use Nsurlsession dataTaskWithURL and create a method to asynchronously download the data 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()
}

Don’t forget to edit info.plist to add to App Transport Security Settings the domain of the search-stand or use https. You will also need to add the file Swiftyjson.Swift to your project.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.