-2

Hi guys I don't know why the array Places returns weird values like 0x6080004b3aa0 instead of displaying my title, coordinate and subtitle out of my JSON url. Thanks for your Help!

import MapKit

@objc class Place: NSObject {


    var title: String?

    var coordinate: CLLocationCoordinate2D
    var subtitle: String?

    init(title:String,subtitle:String, coordinate:CLLocationCoordinate2D){

       self.title = title
        self.coordinate = coordinate
        self.subtitle = subtitle

    }

    static func getPlaces() -> [Place] {
      guard  let url = NSURL(string: "https://script.googleusercontent.com/macros/echo?user_content_key=Z-LfTMdhgAg_6SRd-iMucSyWu-LFBQO8MLxJZ6DPcL05Rtr3joCCypWD2l46qaegSpVpVINc1DLl5inoDOgGx3p3ANpY1AkGOJmA1Yb3SEsKFZqtv3DaNYcMrmhZHmUMWojr9NvTBuBLhyHCd5hHa1ZsYSbt7G4nMhEEDL32U4DxjO7V7yvmJPXJTBuCiTGh3rUPjpYM_V0PJJG7TIaKp4bydEiKBUZP6fpOyGJIhkmEGneM7ZIlWloTVbXmkjs15vHn8T7HCelqi-5f3gf3-sKiW3k6MDkf31SIMZH6H4k&lib=MbpKbbfePtAVndrs259dhPT7ROjQYJ8yx") else { return [] }

        let request = NSMutableURLRequest(url: url as URL!)
         var places = [Place]()
        let task = URLSession.shared.dataTask(with: request as URLRequest) {data,response,error in
            guard error == nil && data != nil else {
                print ("Error:",error)
                return
            }
            let httpStatus = response as? HTTPURLResponse
            if httpStatus?.statusCode == 200
            {  if data?.count != 0
            {
                let responseString = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary


                let contacts = responseString["Sheet1"] as? [AnyObject]

                for contact in contacts!{
                    var places = [Place]()
                    let title = contact["name"] as! String
                    let subtitle = contact["description"] as? String
                    let latitude = contact["latitude"] as? Double ?? 0, longitude = contact["longitude"] as? Double ?? 0


                    let place = Place(title:title,subtitle:subtitle!,coordinate: CLLocationCoordinate2DMake(latitude, longitude))
                     places.append(place)
                    print(latitude)
                    print(place)
                }
             }
            else {
                print("No data got from url")
                }

            } else {
                print("error httpsatus code is:", httpStatus!.statusCode)
            }
        }
        task.resume()


     return places as [Place]
    }


}

I think the problem is this:

let place = Place(title:title,subtitle:subtitle!,coordinate: CLLocationCoordinate2DMake(latitude, longitude))

When I print(place) it returns the weird results

vadian
  • 274,689
  • 30
  • 353
  • 361
Tom
  • 3
  • 3
  • Should I mark this question again as duplicate? Did you read the linked question in your previous one? It's not related to the Swift version. You can't return something from a method containing an asynchronous task in any version of Swift. The reason for the *weird* print result is that your `Place` class lacks a `description` property so you get just the pointer address. – vadian Apr 08 '17 at 17:43
  • I'm sorry @vadian but I tried exactly the same just with a plist and it worked perfectly, so why shouldn't it work with an external json? – Tom Apr 08 '17 at 17:51
  • 1
    Once again, `dataTask` works **asynchronously** – vadian Apr 08 '17 at 17:53

1 Answers1

0

When you make a class that subclasses from NSObject you're creating a object that is backed by an Objective-c class -- which in some circumstances can be really useful (most common use is when you want to take your object and archive it as a blob of binary data).

I'm guessing that in your case, you probably don't want/need to subclass NSObject.

Here's a simplified example to show what's happening:

Here's a class backed by NSObject:

@objc class ObjCPlace: NSObject {
    let name: String
    init(name: String) {
        self.name = name
    }
}

If you create an instance of this object and try to print contents - like you've found, you get the objects location in memory:

let testObjcPlace = ObjCPlace(name: "New York")
print(testObjcPlace)
// prints: 
// <__lldb_expr_310.ObjCPlace: 0x600000055060>

On alternative to using print could be to use dump that provides a more detailed look at your object:

let testObjcPlace = ObjCPlace(name: "New York")
dump(testObjcPlace)
// Prints:
// ▿ <__lldb_expr_310.ObjCPlace: 0x600000055060> #0
//   - super: NSObject
//   - name: "New York"

But instead of making an NSObject subclass, you probably just want to make a Swift class (or in this example a struct take a look at this question and answers for explanations of the differences)

struct Place {
    let name: String
    init(name: String) {
        self.name = name
    } 
}

Because this object isn't an Objective-c object you can use print and get the internal properties printed as well:

let testPlace = Place(name: "New York")
print(testPlace)
// Prints: 
// Place(name: "New York")  

p/s welcome to StackOverflow!

Community
  • 1
  • 1
MathewS
  • 2,267
  • 2
  • 20
  • 31