1

Im trying to make request to multiple URLs to download the HTML and later turn it into a JSON format. Where I'm running into trouble is when i try to make request to multiple URLs in the for loop. I'm no master on this with async requests so, this might be a obvious mistake to you guys, but I can't find a answer to the question.

If I try to run it without the loop (just referencing a single object in the TFHppleElement-array) it seems to work, but as soon as I'm looping it, the request won't seem to be made.

Does not work:

func getData(data: [TFHppleElement]) {

   for index in data{

        let thisurl="https://theurl.org\(index.firstChild.objectForKey("href"))"

        let session = NSURLSession.sharedSession()
        let request = NSMutableURLRequest(URL: NSURL(string: thisurl)!)
        request.HTTPMethod = "GET"

        let task = session.dataTaskWithRequest(request){
            (data : NSData?, response : NSURLResponse?, error : NSError?) -> Void in

            if error == nil{

                let parser = HTMLParser()
                parser.parseNode(data!, xPathString: "//span[@class='odd']", callback: self.createJSON)


            }else{
                print("Request not working")
            }

        }

        task.resume()
    }

}

Works:

func getData(data: [TFHppleElement]) {

  // for index in data{

        let thisurl="https://theurl.org\(data[0].objectForKey("href"))"

        let session = NSURLSession.sharedSession()
        let request = NSMutableURLRequest(URL: NSURL(string: thisurl)!)
        request.HTTPMethod = "GET"

        let task = session.dataTaskWithRequest(request){
            (data : NSData?, response : NSURLResponse?, error : NSError?) -> Void in

            if error == nil{

                let parser = HTMLParser()
                parser.parseNode(data!, xPathString: "//span[@class='odd']", callback: self.createJSON)


            }else{
                print("Request not working")
            }

        }

        task.resume()
    //}

}

I haven't been programming for a while, so I'm sorry if it might be an obvious mistake.

niwim
  • 21
  • 7

0 Answers0