简体   繁体   English

无法获取我的信息数据任务swift 3

[英]Having trouble getting my info out datatask swift 3

I have this function, and I want to fill the locations array with latitude/longitude data that I get in the dataTask function. 我有这个功能,我想用locationTask函数中的纬度/经度数据填充位置数组。

The problem is that the data is only available in the datatask function and outside it, it'll be gone. 问题是数据只在数据任务函数中可用,在它之外,它就会消失。

func getFromDatabase()
{
    var locations: [CLLocationCoordinate2D] = []
    let url = URL(string: URL_DATABASESend)

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        //Here I print the JSON: print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!)
        do{
            if(data != nil){
               let parsedData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [[String:String]]
                    for dic in parsedData! {
                    if let lat = Double(dic["latitude"]!), let long = Double(dic["longitude"]!) {
                        //print(lat)
                        //print(long)
                        var coordinatesToAppend = CLLocationCoordinate2D(latitude: lat, longitude: long)
                        locations.append(coordinatesToAppend)
                    }
                }
            }} catch let error as NSError{
            print(error.localizedDescription)
            return
        }
    }
    task.resume()
}

I don't know how to use a completionhandler and when I do I get a lot of errors (I followed a lot of tutorials/online help topics). 我不知道如何使用完成处理程序,当我这样做时,我会遇到很多错误(我遵循了很多教程/在线帮助主题)。

Does anyone know how to I can get the information out of the function?(can't return the value cause I'm using datatask) I read a lot of topics but none of it solved my problem. 有谁知道如何从函数中获取信息?(无法返回值因为我正在使用数据任务)我读了很多主题,但没有一个解决了我的问题。

Hope to hear something from you guys! 希望听到你们的一些消息!

You need to use a callback to get your content from the closure. 您需要使用回调来从关闭中获取内容。

Your content is this array: var locations: [CLLocationCoordinate2D] so we are going to use a callback like this one: 你的内容是这个数组: var locations: [CLLocationCoordinate2D]所以我们将使用像这样的回调:

completion: @escaping ([CLLocationCoordinate2D])->()

We add it to the method signature: 我们将它添加到方法签名中:

func getFromDatabase(completion: @escaping ([CLLocationCoordinate2D])->())

Then we use it in your code where the content is ready, just after the loop: 然后我们在内容就绪的代码中使用它,就在循环之后:

func getFromDatabase(completion: @escaping ([CLLocationCoordinate2D])->())
{
    var locations: [CLLocationCoordinate2D] = []
    let url = URL(string: URL_DATABASESend)

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        do {
            if data != nil {
                let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [[String:String]]
                for dic in parsedData {
                    if let lat = Double(dic["latitude"]!), let long = Double(dic["longitude"]!) {
                        let coordinatesToAppend = CLLocationCoordinate2D(latitude: lat, longitude: long)
                        locations.append(coordinatesToAppend)
                    }
                }
                // Here the array is ready, we use the completion handler
                completion(locations)
            }
        } catch let error as NSError {
            print(error.localizedDescription)
            return
        }
    }
    task.resume()
}

Then you call your method with a trailing closure like this to get back the array: 然后用这样的尾随闭包调用你的方法来取回数组:

getFromDatabase { (locs) in
    // Here "locs" is your [CLLocationCoordinate2D] array
    print(locs)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM