2017-07-26 103 views
-1

您好我有幾個圖上的點上的服務器JSON格式的文件:創建MapKit點從JSON數據(SWIFT)

[{"ID":"34","CompanyName":"Sruper","Latitude":"33.8886954","Longitude":"35.4911273","Location":"USA","Category":"Automobile "},{"ID":"47","CompanyName":"TechMe","Latitude":"33.8869625","Longitude":"35.5131741","Location":"USA","Category":"Home "},{"ID":"48","CompanyName":"ElectroKey","Latitude":"33.8786214","Longitude":"35.4863271","Location":"USA","Category":"Health & Fitness "}] 

我希望把這些點作爲標記在我的地圖在我的iOS應用。我看了幾頁,但在這裏,但我沒有找到任何東西,我試過的東西不起作用。我正在使用swift 3和Xcode。

我能夠檢索數據作爲數組,但不能把它們放在地圖視圖,因爲它們是數組而不是雙倍我怎麼能做到這一點,循環?我得到的錯誤無法投類型的值「__NSArrayI」(0x112f16dd8)爲「NSNumber的」

我使用雨燕找不到快速的答案,但他們對目標C iOS JSON Array and MapKit

let url = URL(string: "http://file.php") 
    let data = try? Data(contentsOf: url!) 

    let quotesData = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray 

    let CompanyNameArray = quotesData.value(forKey: "CompanyName") 
    let LocationLatitudeArray = quotesData.value(forKey: "Latitude") 
    let LocationLongitudeArray = quotesData.value(forKey: "Longitude") 
struct Location { 
     let title: String 
     let latitude: Double 
     let longitude: Double 
    } 

    let locations = [ 
     Location(title:CompanyNameArray as! String, latitude: LocationLatitudeArray as! Double, longitude: LocationLongitudeArray as! Double), 

    ] 

    let annotations = locations.map { location -> MKAnnotation in 
     let annotation = MKPointAnnotation() 
     annotation.title = location.title 
     annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude) 
     return annotation 
    } 
    mapView.addAnnotations(annotations) 

請幫忙嗎?

回答

0

要訪問數組值,必須使用array [index],如:CompanyNameArray[index]。您應該遍歷數組中的項目,並使用位置填充陣列。

+0

'title:CompanyNameArray [index] as!字符串'不起作用它說類型任何沒有下標成員。我使用Swift,無法找到答案爲迅速,但他們是爲客觀的C [https://stackoverflow.com/questions/14802618/ios-json-array-and-mapkit] – CoderJ13

+0

我認爲你沒有得到數組,您是否已經完成調試以檢查'CompanyNameArray'值?它顯示了什麼? –