4

The objective is this:

  • Calculate the lat and long of each item in my array
  • Append the lat and long to an array
  • Print all items in the array in the max distance.

Here is how I'm pulling data in:

import Foundation
import SwiftyJSON

class restaurant {

    //Json
     var id: Int!
     var name: String!
     var address: String!
     var city: String!
     var logo: String!
     var state: String!
     var postKey: String!


    //Second
    var ids: Int!
    var names: String!
    var aAddress: String!
    var citys: String!
    var logos: String!
    var states: String!

    var distance : Double = 0

    //Importing data from server. Bring moto. Make sure you are able to get details in postman prior to adding any other variables
    init(json: JSON) {
        self.id = json["id"].int
        self.name = json["dispensary_name"].string
        self.address = json["street_address"].string
        self.logo = json["logo"].string
        self.city = json["city"].string
        self.state = json["state"].string
    }

    init(postKey: String, postData: Dictionary<String, AnyObject>) {
        self.postKey = postKey

//        self.ids = postData[self.id]?.int
        self.names = postData[self.name]?.string
        self.aAddress = postData[self.address]?.string
        self.citys = postData[self.city]?.string
        self.logos = postData[self.logo]?.string
        self.states = postData[self.state]?.string
    }
}

Here is my array: //Loads list of restaurants.

func loadRestaurants() {
    Helpers.showActivityIndicator(activityIndicator, view)

    APIManager.shared.getRestaurants { (json) in
        if json != nil {
            self.restaurants = []
                //Adds all items into the array list dist then goes through them all.
            if let listDis = json["restaurant"].array {
                for item in listDis {

                    let address = item["street_address"].string! + ", " + item["city"].string! + ", " + item["state"].string!

                    self.getLocation(address, { (dis) in
                                        self.disLocation = dis
                    })

                    //snap = item, snapshot = listdict

                    if let snapValue = item.array as? [String:AnyObject],
                       let venueLat = self.disLocation?.coordinate.latitude,
                       let venueLong = self.disLocation?.coordinate.longitude {
                        print("snapValue ,", snapValue)
                        let distance = self.calculateDistance(userlat: self.userLatt, userLon: self.userLonn, venueLat: venueLat, venueLon: venueLong)

                        if distance <= 15 {
                            let key = item.string
                            let restaurant = Restaurant(postKey: key!, postData: snapValue)
                            restaurant.distance = distance
                            self.restaurants.append(restaurant)
                            print("restaurant :", snapValue)
                        }
                    }
                }

                if self.restaurants.count == 0 {
                    let alert = UIAlertController(title: "Oh No!!!", message: "We Only Deliver To New Jersey", preferredStyle: UIAlertControllerStyle.alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
                         }))
                    self.present(alert, animated: true, completion: nil)
                }
                self.restaurants.sort {                                
                    $0.distance < $1.distance
                }
            }
            self.restaurants.reloadData()
            Helpers.hideActivityIndicator(self.activityIndicator)
        }
    }
}

I'm not sure what I should do here. Any advice would be helpful.

Output of Item:

"state" : "New Jersey",
  "city" : "Highland Park",
  "id" : 3,
  "dispensary_name" : "Down South Taste",
  "street_address" : "4422 knotwood ct",
  "zip_Code" : 56430,
  "phone" : "444-334-0888",
  • I've tried with the debugger sir. If I could fix it on my own, I would. – Doing Things Occasionally May 20 '18 at 23:38
  • that does not answer the question, what does your step debugger tell you? –  May 20 '18 at 23:38
  • It's not the debugger. It's me. I'm not sure how to iterate through this loop while attaching the locations per restaurant. I don't know where to start as I tried to append the array to the PostData but, that does not work. It always returns nil when trying to append and sort. You're coming off very condescending and Im sure that's not what you meant. I just need to know how to do this task because, logically, I do not understand how to make it work. – Doing Things Occasionally May 21 '18 at 00:28
  • If I print out the loop of all locations, I get my locations. When trying to sort it, thats where the issue here in lies. – Doing Things Occasionally May 21 '18 at 00:29
  • 1
    I think you need to re-read the documentation on how to use `.sort()` correctly. there are plenty of [duplicates](https://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value) here explaining what you are doing wrong. –  May 21 '18 at 04:00
  • 2
    Since you do not ask a specific question it is not surprising you are not getting any answers. Try to reduce the scope of your method and ask about the part that is not working as you expect. Load your `JSON` in one method. Use another method to calculate distances, a third one to filter and another one to sort. That way you will have only simple problems to solve and you can concentrate on one thing. Try to post a reduced example with complete input (e.g. a JSON-string) and post the output as well. Then you would have to tell us about your expectations and why they are not met. – Patru May 21 '18 at 16:40
  • if your sort is coming out as empty then likely it means that your array was empty. I mean if your sorting isn't done right then it would just be sorted in the wrong way. But if it's empty then it just means you **haven't** populated (appended items to your array) correctly – mfaani May 22 '18 at 15:08
  • Instead of offering a bounty you should opt for asking a more precise question. Please post your raw `JSON` and print out your `listDis` in order to give us a hint of what is going wrong. People will be glad to fix a failing test case for you, it is however rare that people try to figure out what your application should do. – Patru May 27 '18 at 20:44
  • Patru the output is up there now. You can see the output of item as listDict just give the number of objects without object details. – Doing Things Occasionally May 28 '18 at 00:07
  • Since you do not post the code for the printing I have to do some more guesswork. I gather this is the contents of a single `item` (not of `lisDis`, but fair enough). So you seem to get some data, but your `getLocation` function (which has a weird piece of interface by the way) is nowhere to be found. Do you know if it is putting _some_ distance _anywhere_? You will have to be _a lot_ more specific than this in order to get an answer. – Patru May 30 '18 at 17:12

1 Answers1

0

The init method you use for your Restaurant object (the second one) is clearly wrong and will lead to a runtime crash since you are unwrapping nil values.

self.names = postData[self.name]?.string 

name is nil here but declared as

var name: String!

I don't really understand what you're trying to achieve when reading a dictionary using properties as keys instead of string constants?

Maybe do something like

let nameKey = "dispensary_name"
...

self.names = postData[nameKey]?.string 

If I understand it correctly your program doesn't crash which tells us that the constructor is never called. My guess is that it is the condition in the surrounding if statement that fails and the first part of the condition looks wrong where you call .array on your json item and typecast the result as a dictionary

if let snapValue = item.array as? [String:AnyObject], ...

.array. looks wrong here and while I don't know your json format you earlier access the item property as a dictionary, isn't it item that is your dictionary.

Hopefully this will help you to move forward.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52