iOS - calling Webservice and parsing JSON in Swift

2019-06-09 13:44发布

I am using NSURLSession to call my own Webservice which returns JSON, works fine with this code:

func getJSONFromDatabase(){
    let url = NSURL(string: "http://www.myurl/mysqlapi.php")

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        self.json = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print(self.json)
    }
    task.resume()
}

However, it seems that this Task is not executed in the right order, because when i run the following function after the "getJSONFromDatabase" function, the "print" statement in the Task is executed after the "print" statement from the "parseJSON" function.

func parseJSON(){

    let data = self.json.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

    do {
        let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSArray

        for event in json {
            let name = event["name"]
            let startDate = event["startDate"]


            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"
            let date = dateFormatter.dateFromString(startDate as! String)


            if date != nil {
                self.events.append(Event(name: name as! String, startDate: date!))
            }
            else {
                print("Date is nil")
            }
        }

        for event in self.events {
            print(event.name)
        }
    } catch let error as NSError {
        print("Failed to load: \(error.localizedDescription)")
    }
}

My goal is to save the JSON Data in an Object Array of "Event", but this doesn't seem to work because when i iterate over my "self.events" array, it is empty.

Another problem is: When i split this 2 things like i posted here (2 functions), the "parseJSON" throws an error:

Failed to load: The data couldn’t be read because it isn’t in the correct format.

However, if i add the content of "parseJSON" into the Task of the "getJSONFromDatabase" function, there is no such error, but the array is still empty

1条回答
你好瞎i
2楼-- · 2019-06-09 14:08

dataTaskWithURL is asynchronous so you your code won't execute from the top down. Use a completion handler to work on the result from the asynchronous call.

func getJSONFromDatabase(success: ((json: String)->())){
    let url = NSURL(string: "http://www.myurl/mysqlapi.php")

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        let json = NSString(data: data!, encoding: NSUTF8StringEncoding)
        success(json: json)
    }
    task.resume()
}

in use

getJSONFromDatabase(success: {json in 
    //do stuff with json
})
查看更多
登录 后发表回答