首页 > 解决方案 > 将徽标快速添加到 tableview 并根据建议的里程排列显示的数组

问题描述

这是代码。他们从 google 地方获取 atm 位置并显示在 tableview 上。

     /**
 Calculates the distance between the user and a given location
 - Parameters:
 - location: ATM location coordinate
 */
func calculateDistance(location: CLLocationCoordinate2D) -> String {

    let distanceLocation = CLLocation(latitude: location.latitude, longitude: location.longitude)

    var distance = self.lastLocation!.distance(from: distanceLocation)

    let locationInFoot = distance * 3.28084

    var locationString = String(format: "%d ft", Int(locationInFoot))

    if locationInFoot > 656.168 {
        // Over 200ft
        distance = distance / 1609.34

        locationString =  String(format: "%.01f miles", distance)
       }

       return locationString

       }

    class PlacesAPIManager : NSObject {

static let instance = PlacesAPIManager()
var session = URLSession.shared

/**
 Used to trigger the Google Places API Request
 - parameters:
 - completion : Array of ATM objects
 */


    func determineAtmsNearby(completion : @escaping ([ATM]) -> Void){

       let placesSearchComponent = NSURLComponents()
        placesSearchComponent.scheme = "https"
       placesSearchComponent.host = Constants.basePlacesURL
       placesSearchComponent.path = "/maps/api/place/nearbysearch/json"

       // Build the query items for the api request
    let radiusQueryItem = URLQueryItem(name: "radius", value: "20000")
    let typeQueryItem = URLQueryItem(name: "type", value: "atm")
    let apiQueryItem = URLQueryItem(name: "key", value: 
     Constants.APIKey)
    let location = URLQueryItem(name: "location", value: 
    LocationManager.instance.getCoordinateString())


    placesSearchComponent.queryItems = [radiusQueryItem, typeQueryItem, apiQueryItem, location]

    let request = NSMutableURLRequest(url: placesSearchComponent.url!,cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)

    request.httpMethod = "POST"

    session.dataTask(with: request as URLRequest, completionHandler: { 
      (data, response, error) -> Void in

        var places : [ATM] = []

        if let data = data,

            let json = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {

            let results = json?.object(forKey: "results") as? NSArray

            for place in results! {

                do {
                    let place = try ATM(atmDictionary: place as! NSDictionary)
                    places.append(place)
                } catch {
                    completion([])
                }
            }
            completion(places)
        }

    }).resume()

}

}

自动柜员机类

    class ATM : NSObject, MKAnnotation {

let title : String?
let latitude : Double
let longitude : Double
var subtitle : String?
var coordinate: CLLocationCoordinate2D

init(atmDictionary : NSDictionary)throws{

    // Error handling
    guard let name = atmDictionary["name"] as? String else {
        throw SerializationError.missing("name")
    }
    guard let geometry = atmDictionary["geometry"] as? NSDictionary else {
        throw SerializationError.missing("gemoetry")
    }
    guard let location = geometry["location"] as? NSDictionary else {
        throw SerializationError.missing("location")
    }
    guard let latitude = location["lat"] as? Double else {
        throw SerializationError.missing("latitude")
    }
    guard let longitude = location["lng"] as? Double else {
        throw SerializationError.missing("longitude")
    }

    // Initialise Properties
    self.title = name
    self.longitude = longitude
    self.latitude = latitude
    self.coordinate = CLLocationCoordinate2D(latitude: self.latitude, longitude: self.longitude)

    // Initially this is not calculated
    self.subtitle = "N/L"

}

/**
 Used to update the Atm object with the distance from the user as the value for 'subtitle' property
 - parameters:
 - coordinate : Coordinate
 */
    func updateAtmLocation(coordinate : CLLocationCoordinate2D){
    self.subtitle = 
    LocationManager.instance.calculateDistance(location: coordinate)
      }

       }

ATM清单类

      class AtmList: NSObject {

static let instance = AtmList()

var atms : [ATM] = []

func addAtm(atm : ATM){
    atms.append(atm)
}

func resetAtmList(){
    atms = []
}

func getAtmsCount() -> Int{
    return atms.count
}

func udpateAtms(index : Int, coordinate : CLLocationCoordinate2D){
    atms[index].updateAtmLocation(coordinate: coordinate)
}

}

我有两个问题:

  1. 我想从最低距离到最高距离排列显示
  2. 我想获取每家银行的徽标并将其显示在 tableview 列表中每个名称的旁边。

标签: swiftgoogle-mapsuitableview

解决方案


1.)

在 ATM 类中,我将创建一个表示距离的新属性 - 每次计算距离时,也要更新该属性。这将使您能够按距离对 ATM 阵列进行排序。

将 ATM 附加到数组后,您可以使用以下方法对数组进行排序:

places = places.sort({$0.distance < $1.distance})

2.)

请提供有关银行的更多信息:您是否有自定义对象,您有图片/图片网址吗?


推荐阅读