iOS-调用Webservice并在Swift中解析JSON [英] iOS - calling Webservice and parsing JSON in Swift

查看:125
本文介绍了iOS-调用Webservice并在Swift中解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NSURLSession调用我自己的返回JSON的Web服务,该代码可以正常工作:

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()
}

但是,似乎此任务未按正确的顺序执行,因为当我在"getJSONFromDatabase"函数之后运行以下函数时,任务中的"print"语句在从"parseJSON"功能.

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)")
    }
}

我的目标是将JSON数据保存在事件"的对象数组中,但这似乎不起作用,因为当我遍历"self.events"数组时,它为空.

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.

另一个问题是:当像我在此处发布的那样拆分这2件事(2个函数)时,"parseJSON"会引发错误:

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.

但是,如果我将"parseJSON"的内容添加到"getJSONFromDatabase"函数的任务中,则不会出现此类错误,但是数组仍为空

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

推荐答案

dataTaskWithURL是异步的,因此您的代码将不会自上而下执行.使用完成处理程序来处理异步调用的结果.

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()
}

使用中

getJSONFromDatabase(success: {json in 
    //do stuff with json
})

这篇关于iOS-调用Webservice并在Swift中解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆