2017-08-31 58 views
0

我創建了一個用於下載數據的網絡文件,並且我想將數據分配給另一個視圖控制器,以便我可以使用註釋填充地圖。數據下載成功,但我無法將其分配給視圖控制器。當我將網絡代碼包含在視圖控制器中並使用DispatchQueue.main.async時,我只能使它工作。我想保持網絡文件和視圖控制器分開。任何見解將不勝感激。提前爲許多代碼行道歉。使用Grand Central調度Swift分配數據3

聯網文件如下:

import UIKit 

class Networking { 

static let shared = Networking() 

var objects = [Any]() 

func getData (_ completionHandler:@escaping (Location?) ->()) { 

    //Create the url with NSURL reuqest 
    let url = URL(string: "http://localhost:3000/locations") 

    let request = NSMutableURLRequest(url: url! as URL) 

    //Set HTTP method as GET 
    request.httpMethod = "GET" 

    //HTTP Headers 
    request.addValue("application/json", forHTTPHeaderField: "Accept") 

    //Create dataTask using the session object to send data to the server 
    URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in 

     guard let data = data, 
      let dataStore = String(data: data, encoding: String.Encoding.utf8) else { 
       print("Could not find network") 
       completionHandler(nil) 
       return 
     } 

     guard error == nil else { 
      print("Error calling GET") 
      completionHandler(nil) 
      return 
     } 

     let HTTPResponse = response as! HTTPURLResponse 
     let statusCode = HTTPResponse.statusCode 

     if (statusCode == 200) { 
      print("Files downloaded successfully. \(dataStore)") 
     } else { 
      completionHandler(nil) 
      return 
     } 

     //Create json object from data 
     do { 

      let json = try! JSONSerialization.jsonObject(with: data , options: []) as? [[String: Any]] 
let location: [Location] = [] 

      if let array = json { 

       for i in 0 ..< array.count { 

        if let data_object = array[i] as? [String: Any] { 

         if let _id = data_object["_id"] as? String, 
          let name = data_object["name"] as? String, 
          let imageID = data_object["imageID"] as? String, 
          let category = data_object["category"] as? String, 
          let details = data_object["details"] as? String, 
          let latitude = data_object["latitude"] as? Double, 
          let longitude = data_object["longitude"] as? Double { 

          var dictionary = [_id, name, imageID, category, details, latitude, longitude] as [Any] 

          dictionary.append(location) 

         } 
        } 
       } 
      } 
     } 

     }.resume() 
    } 
} 

的模型是如下:

class Location { 

var _id : String 
var name : String 
var imageID : String 
var category : String 
var details : String 
var latitude : Double 
var longitude : Double 

init?(_id: String, name: String, imageID: String, category: String, details: String, latitude: Double, longitude: Double) { 

    self._id = _id 
    self.name = name 
    self.imageID = imageID 
    self.category = category 
    self.details = details 
    self.latitude = latitude 
    self.longitude = longitude 

    } 
} 

視圖控制器如下:

class MapViewController: UIViewController, MGLMapViewDelegate, UIGestureRecognizerDelegate { 

override func viewDidLoad() { 
    super.viewDidLoad() 

    mapView.delegate = self 


    Networking.shared.getData { (locations) in 


    } 

    populateMap() 

} 

func populateMap(){ 

    let point = MGLPointAnnotation() 
    for location in locations { 
     let coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude) 
     point.coordinate = coordinate 
     point.title = location.name 
     point.subtitle = location.category 
     self.mapView.addAnnotation(point) 

    } 
} 
+0

您可以用'NotificationCenter'做到這一點。有關'NotificationCenter'的更多信息,請參閱https://developer.apple.com/documentation/foundation/notificationcenter – Venkat

回答

1

您正在執行完成塊只有在失敗的情況下。一旦您設法分析數據並將數組作爲參數傳遞給閉包/塊,請執行完成塊。

import UIKit 

class Networking { 

static let shared = Networking() 

var objects = [Any]() 

func getData (_ completionHandler:@escaping ([Location]?) ->()) { 

    //Create the url with NSURL reuqest 
    let url = URL(string: "http://localhost:3000/locations") 

    let request = NSMutableURLRequest(url: url! as URL) 

    //Set HTTP method as GET 
    request.httpMethod = "GET" 

    //HTTP Headers 
    request.addValue("application/json", forHTTPHeaderField: "Accept") 

    //Create dataTask using the session object to send data to the server 
    URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in 

     guard let data = data, 
      let dataStore = String(data: data, encoding: String.Encoding.utf8) else { 
       print("Could not find network") 
       completionHandler(nil) 
       return 
     } 

     guard error == nil else { 
      print("Error calling GET") 
      completionHandler(nil) 
      return 
     } 

     let HTTPResponse = response as! HTTPURLResponse 
     let statusCode = HTTPResponse.statusCode 

     if (statusCode == 200) { 
      print("Files downloaded successfully. \(dataStore)") 
     } else { 
      completionHandler(nil) 
      return 
     } 

     //Create json object from data 
     do { 

      let json = try! JSONSerialization.jsonObject(with: data , options: []) as? [[String: Any]] 
let location: [Location] = [] 

      if let array = json { 

       for i in 0 ..< array.count { 

        if let data_object = array[i] as? [String: Any] { 

         if let _id = data_object["_id"] as? String, 
          let name = data_object["name"] as? String, 
          let imageID = data_object["imageID"] as? String, 
          let category = data_object["category"] as? String, 
          let details = data_object["details"] as? String, 
          let latitude = data_object["latitude"] as? Double, 
          let longitude = data_object["longitude"] as? Double { 

          var dictionary = [_id, name, imageID, category, details, latitude, longitude] as [Any] 

          dictionary.append(location) //am not sure of what this means test your code 

          completionHandler(location) 
         } 
        } 
       } 
      } 
     } 

     }.resume() 
    } 
} 

在你的代碼少犯更多的錯誤:

  1. 你完成塊的預計位置作爲參數。但在你的代碼中你正在創建一個位置數組。

    設的位置:[位置] = []

因此,我已修改完成塊參數返回的位置陣列

  • 在您的循環要創建

    VAR詞典= [_id,名稱,圖像標識,類別,細節,緯度,經度]爲[任何]

  • 並將其追加到dictionary.append(位置)我不知道這段代碼是什麼。我相信什麼ü真正要做的是創建一個從數據的位置對象,然後將其添加到位置陣列

    location.append(your_new_location_object) 
    

    希望它可以幫助

    +1

    我修改了代碼,現在它可以工作。 –

    +0

    @ j-hooper:很高興你解決了這個問題:)快樂的編碼 –

    相關問題