dsf487787 2018-06-24 18:38 采纳率: 100%
浏览 108
已采纳

如何在执行函数之前等待Swift中的变量? (迅速)

below is my code. I want the value for Latitude and Longitude in my Poststring. But When he do the poststring my values are still nil because swift didn't update the location yet. So how can I wait for latitude and longitude before poststring gets the Values? I heard something of didset but I don't know how to use it and where I have to use it.

import Foundation
import CoreLocation


protocol FeedmodelProtocol: class {
    func itemsDownloaded(items: NSArray)
}


class Feedmodel: NSObject, URLSessionDataDelegate, CLLocationManagerDelegate {



    weak var delegate: FeedmodelProtocol!
    let locationManager = CLLocationManager() // create Location Manager object
    var latitude : Double?
    var longitude : Double?

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location: CLLocationCoordinate2D = manager.location?.coordinate else { return }
        // set the value of lat and long
        latitude = location.latitude
        longitude = location.longitude

    }

    func downloadItems() {
        self.locationManager.requestAlwaysAuthorization()

        // For use in foreground
        // You will need to update your .plist file to request the authorization
        self.locationManager.requestWhenInUseAuthorization()

        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters

            locationManager.startUpdatingLocation()

        }
        let myUrl = URL(string: "http://example.com/stock_service4.php");
        let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
        var request = URLRequest(url:myUrl!)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        var postString = ""
        if let lat = latitude, let long = longitude {
            locationManager.stopUpdatingLocation()
            postString = "lati=\(Int(lat))&longi=\(Int(long))"
            // do task here now that postString is not empty
        }
        request.httpBody = postString.data(using: .utf8)
        let task = defaultSession.dataTask(with: request) { data, response, error in


            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(String(describing: error))")
                return

            }


            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
                print("error=\(String(describing: error))")
            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(String(describing: responseString))")
            print("error=\(String(describing: error))")
            self.parseJSON(data)

        }

        task.resume()

    }

    func parseJSON(_ data:Data) {

        var jsonResult = NSArray()

        do{
            jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray;
        } catch let error as NSError {
            print(error)

        }

        var jsonElement = NSDictionary()
        let stocks = NSMutableArray()

        for i in 0 ..< jsonResult.count
        {
            print(jsonResult)
            jsonElement = jsonResult[i] as! NSDictionary


            let stock = Stockmodel()

            //the following insures none of the JsonElement values are nil through optional binding
            if  let Datum = jsonElement["Datum"] as? String,
                let Tankstelle = jsonElement["Tankstelle"] as? String,
                let Kraftstoff1 = jsonElement["Kraftstoff1"] as? String,
                let Preis1 = jsonElement["Preis1"] as? String,
                let Kraftstoff2 = jsonElement["Kraftstoff2"] as? String,
                let Preis2 = jsonElement["Preis2"] as? String,
                let Notiz = jsonElement["Notiz"] as? String,
                let longitude = jsonElement["longitude"] as? String,
                let latitude = jsonElement["latitude"] as? String



            {
                print (Datum)
                print(Tankstelle)
                print(Kraftstoff1)
                print(Preis1)
                print(Kraftstoff2)
                print(Preis2)
                print(Notiz)
                print(longitude)
                print(latitude)
                stock.Datum = Datum
                stock.Tankstelle = Tankstelle
                stock.Kraftstoff1 = Kraftstoff1
                stock.Preis1 = Preis1
                stock.Kraftstoff2 = Kraftstoff2
                stock.Preis2 = Preis2
                stock.Notiz = Notiz
                stock.longitude = longitude
                stock.latitude = latitude


            }

            stocks.add(stock)

        }

        DispatchQueue.main.async(execute: { () -> Void in

            self.delegate.itemsDownloaded(items: stocks)

        })
    }
}

Thank You!

  • 写回答

1条回答 默认 最新

  • dougong1031 2018-06-24 19:10
    关注

    The function locationManager(_:didUpdateLocations:) is called every time when the location is update. So you should add downloadItems() in the location manager like this :

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location: CLLocationCoordinate2D = manager.location?.coordinate else { return }
    
        // set the value of lat and long
    
        latitude = location.latitude
        longitude = location.longitude
    
        downloadItems()
    }
    

    See the documentation about locationManager(_:didUpdateLocations:)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛