0

I've been trying to make this to work for two weeks now. It was working on iOS 9 with Swift 2 but now this doesn't seem to work for no reason. I've added print("[DEBUG] I was here 1/2/3/4") to debug the code and all it prints out is [DEBUG] I was here 1. Any ideas? It drives me crazy.

func downloadData() {
    //clear the arrays
    arrayPosts = [String]()
    arrayLinks = [String]()
    arrayConditions = [String]()
    arrayIDs = [String]()
    //debug
    print("[DEBUG] I was here: 1")

    //baseURL is a string with URL to JSON Endpoint
    let url = URL(string: baseURL)
    URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
        if error != nil {
            print("[ERROR] [DEBUG] Error with connection: \(error)")
        } else {
            do {
                //debug
                print("[DEBUG] I was here: 2")
                if let json = try JSONSerialization.jsonObject(with: data!, options:[.mutableContainers, .allowFragments]) as? [[String: Any]] {
                    for item in json {
                        //debug
                        print("[DEBUG] I was here: 3")
                        if let startTime = item["current_time"] as? Int {
                            if self.defaults.integer(forKey: "startTime") == 0 {
                                self.defaults.set(startTime, forKey: "startTime")
                            }
                        }

                        if let posts = item["posts"] as? [[String: AnyObject]] {
                            //debug
                            print("[DEBUG] I was here: 4")
                            for post in posts {
                                if let text = post["text"] as? String {
                                    if let condition = post["conditions"] as? String{
                                        if let url = post["url"] as? String {
                                            if let id = post["id"] as? String {
                                                self.arrayPosts.append(text)
                                                self.arrayConditions.append(condition)
                                                self.arrayLinks.append(url)
                                                self.arrayIDs.append(id)
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            } catch {
                print("[ERROR] [DEBUG] Something went wrong during data download from the server.")
            }
        }

    }).resume()
}

Here's JSON DATA just in case:

{
    "status": "ok",
    "num_results": "4",
    "current_time": 1474386061,
    "user_time": 0,
    "posts": [
    {
        "text": "If your shirt isn't tucked into your pants, then your pants are tucked into your shirt.",
        "conditions": "4",
        "url": "0",
        "time": "0",
        "id": "108"
    },
    {
        "text": "Veteran Kills Himself in Parking Lot of V.A. Hospital on Long Island",
        "conditions": "6",
        "url": "http://www.nytimes.com/2016/08/25/nyregion/veteran-kills-himself-in-parking-lot-of-va-hospital-on-long-island.html",
        "time": 1472076000,
        "id": "1472076000"
    },
    {
        "text": "Leaked Script Shows What Advisers Want Donald Trump to Say at Black Church",
        "conditions": "6",
        "url": "http://www.nytimes.com/2016/09/02/us/politics/donald-trump-black-voters-wayne-jackson.html",
        "time": 1472767200,
        "id": "1472767200"
    },
    {
        "text": "Creepy Clown Sightings in South Carolina Cause a Frenzy",
        "conditions": "6",
        "url": "http://www.nytimes.com/2016/08/31/us/creepy-clown-sightings-in-south-carolina-cause-a-frenzy.html",
        "time": 1472594400,
        "id": "1472594400"
    }
    ]
}
  • I've just tested with a fake URL and it goes to "[DEBUG] I was here: 2". – Eric Aya Sep 20 '16 at 13:42
  • Is `let url = URL(string: baseURL)` nil? – Larme Sep 20 '16 at 13:46
  • @EricAya In theory it should. I ran it again just in case yet it stops at "[DEBUG] I was here: 1". Could be something else wrong? Like the fact that I'm using http instead of https? –  Sep 20 '16 at 13:55
  • No, @Larme it isn't –  Sep 20 '16 at 13:55
  • @EricAya There are no errors regarding Application Transport Security. Though I get an error from another function later on "fatal error: unexpectedly found nil while unwrapping an Optional value" and it's coming from Core Data. Could this influence anything in anyway? –  Sep 20 '16 at 14:10
  • can you update your question with JSON data? – Rajamohan S Sep 20 '16 at 14:44
  • @MohanSingh here we go –  Sep 20 '16 at 15:44
  • Ok I think I know what could be the issue. I've set the breakpoint and the app stoped before it even though in theory it should. In the Swift 2 version I've used Semaphores to force the app to download JSON data before continuing but in Swift 3 I removed them because they stoped working and never added an alternative. Any suggestions? –  Sep 20 '16 at 16:25
  • @MaticConradi , check my answer below. – Rajamohan S Sep 21 '16 at 08:28
  • @MaticConradi , why are here people not responding, when they get answer. I just wanna response as thanks or did not work for my waste of time. If my answer not compatible with you, i will delete it. – Rajamohan S Sep 23 '16 at 01:14
  • 1
    @MohanSingh sorry for late response. I've solved the problem before you've answered. Thanks anyway. –  Sep 23 '16 at 13:13

3 Answers3

4

Try below code :

import UIKit

class ViewController: UIViewController {

   var arrayPosts = [String]()
   var arrayLinks = [String]()
   var arrayConditions = [String]()
   var arrayIDs = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.downloadData()

    }

    func downloadData()
    {
        let url = NSURL(string: "http://getmydetails.pe.hu/test/parsejsonswift3.php") //Provided JSON data on my server. i don't know how longer it is present there!.
        let request = NSMutableURLRequest(url: url! as URL)

        let task = URLSession.shared.dataTask(with: request as URLRequest) { data,response,error in
        guard error == nil && data != nil else
        {
            print("Error:",error)
            return
            }

            let httpStatus = response as? HTTPURLResponse

            if httpStatus!.statusCode == 200
            {
                if data?.count != 0
                {
                    let responseString = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary //because JSON data started with dictionary. Not an array
                    let status = responseString["status"] as! String

                    if status == "ok"
                    {
                        print("Status is :", status)

                        let timevar = responseString["current_time"] //not specified as String or Int
                        print(String(describing: timevar)) // print by converting anyobject to string

                       if let posts = responseString["posts"] as? [AnyObject] // posts started with array
                        {
                        for post in posts
                            {
                                let text = post["text"] as! String //specify as String
                                print(text)

                                let condition = post["conditions"] as! String
                                let url = post["url"] as! String
                                let id = post["id"] as! String
                                DispatchQueue.main.sync
                                {

                                    self.arrayPosts.append(text)
                                    self.arrayConditions.append(condition)
                                    self.arrayLinks.append(url)
                                    self.arrayIDs.append(id)

                                    //optional to check
                                    self.afterJSON()
                                }
                            }
                        }
                        else
                        {
                            print("I could not find post array")
                        }
                    }
                    else
                    {
                        print("Status is not Okay!")
                    }
                }
                else
                {
                    print("No data got from url!")
                }
            }
            else
            {
                print("error httpstatus code is :",httpStatus!.statusCode)
            }
        }
        task.resume()
    }

    func afterJSON()
    {
        print("Posts are:\n\t\t",arrayPosts)
        print("Conditions are:\n\t\t",arrayConditions)
        print("Links are:\n\t\t",arrayLinks)
        print("ID's are:\n\t\t",arrayIDs)

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

Output is like below screenshot,

enter image description here

If you confuse then see my video is for you.

If any queries please comment below :D

Rajamohan S
  • 7,229
  • 5
  • 36
  • 54
0
func downloadData() {
    //clear the arrays
    arrayPosts = [String]()
    arrayLinks = [String]()
    arrayConditions = [String]()
    arrayIDs = [String]()
    //debug
    print("[DEBUG] I was here: 1")

    //baseURL is a string with URL to JSON Endpoint
    let url = URL(string: baseURL)
    let session = URLSession.shared

    let task = session.dataTask(with: url!) { (data:Data?, response:URLResponse?, error:Error?) in
        if error != nil {
            print("[ERROR] [DEBUG] Error with connection: \(error)")
        } else {
            do {
                //debug
                print("[DEBUG] I was here: 2")
                if let json = try JSONSerialization.jsonObject(with: data!, options:[.mutableContainers, .allowFragments]) as? [[String: Any]] {
                    for item in json {
                        //debug
                        print("[DEBUG] I was here: 3")
                        if let startTime = item["current_time"] as? Int {
                            if self.defaults.integer(forKey: "startTime") == 0 {
                                self.defaults.set(startTime, forKey: "startTime")
                            }
                        }

                        if let posts = item["posts"] as? [[String: AnyObject]] {
                            //debug
                            print("[DEBUG] I was here: 4")
                            for post in posts {
                                if let text = post["text"] as? String {
                                    if let condition = post["conditions"] as? String{
                                        if let url = post["url"] as? String {
                                            if let id = post["id"] as? String {
                                                self.arrayPosts.append(text)
                                                self.arrayConditions.append(condition)
                                                self.arrayLinks.append(url)
                                                self.arrayIDs.append(id)
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            } catch {
                print("[ERROR] [DEBUG] Something went wrong during data download from the server.")
            }
        }

    }
    task.resume()
}
Bista
  • 7,869
  • 3
  • 27
  • 55
torinpitchers
  • 1,282
  • 7
  • 13
  • That doesn't seem to work. It stops at "[DEBUG] I was here 1" again. –  Sep 20 '16 at 15:39
0

thanks man I follow your code an got data))

    func getJSON(){
    let wUrl = "http://api.fixer.io/latest"
    let Url = NSURL(string: wUrl)
    let request = NSMutableURLRequest(url: Url! as URL)

    let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in
        guard error == nil && data != nil else
        {
            print("Error:", error ?? "some error")
            return
        }

        let httpStatus = response as? HTTPURLResponse
        if httpStatus!.statusCode == 200 {
            if data?.count != 0 {

                let resposeString = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary

                let base = resposeString["base"] as? String
                print(base ?? "")
                let date = resposeString["date"] as? String
                print(date ?? "")
                let rates = resposeString["rates"] as! Dictionary<String, AnyObject>

                for (key, value) in rates{
                    print("\(key)->\(value)")

                }
            }
            else
            {
                print("Data is emty")
            }
        }
        else {
            print("error httpStatus code: ", httpStatus?.statusCode ?? "")
        }

    };task.resume()


}
Ernist Isabekov
  • 1,205
  • 13
  • 20