Issue saving GeoPoint to a DB/Heroku - heroku

I have code like this to take an object in Core Data and save it to a mLab database, working with Heroku.
// item is an NSManagedObject ....
var dataDict:[String:AnyObject]
dataDict = ["name": item.valueForKey("name") as! String,
"address": item.valueForKey("address") as! String]
let gpsStr = item.valueForKey("gPS") as! String,
commaRange = gpsStr.rangeOfString(","),
gPS = PFGeoPoint(latitude: Double(gpsStr.substringToIndex((commaRange?.startIndex)!))!,
longitude: Double(gpsStr.substringFromIndex((commaRange?.endIndex)!))!)
dataDict["gPS"] = gPS
let parse_Object = PFObject(className: "TheGoodClass", dictionary: dataDict)
parse_Object.saveInBackgroundWithBlock { (succeeded: Bool, error: NSError?) in
if (succeeded) {
print("IT all went RIGHT")
} else {
print("IT all went WRONG")
}
}
When running it I get this kind of error message:
.... [Error]: schema mismatch for TheGoodClass.gPS; expected String but got GeoPoint (Code: 111, Version: 1.12.0)
IT all went WRONG
I don't understand why a String is expected here.
I want a GeoPoint and not a String. What do I need to do?

Related

Swift: Could not cast value of type 'Could not cast value of type '__NSCFString' (0x10e4d5ef0) to 'NSDictionary' (0x10e4d6bc0).'

I am trying to get post data in dictionary. Let first me show what I am doing.
manager.POST(url, parameters: dict,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
if let jsonDict = self.parseJSON(responseObject) {
print(jsonDict)
// Error occur on the following line
let dataDict = jsonDict["data"] as! [String : AnyObject]
// Error Info: Swift: Could not cast value of type 'Could not cast value of type '__NSCFString' (0x10e4d5ef0) to 'NSDictionary' (0x10e4d6bc0).'
}
ParseJson Function:
func parseJSON(inputData: AnyObject) -> Dictionary<String,AnyObject>?{
do {
let jsonDict = try NSJSONSerialization.JSONObjectWithData(inputData as! NSData, options:NSJSONReadingOptions.MutableContainers) as! Dictionary<String,AnyObject>
// use jsonData
return jsonDict
} catch let error as NSError {
// report error
print(error.description)
print("Session: Json Parse Error!!!")
return nil
}
}
This is the result of pirnt(jsonDict)
[data: {"session_id":"ab4kn9fj34ko89kjkl5ljs98gfk498fgkl409alk34l","user_info":{"username":"Johny Cage","ENCPASSWORD":"johnycage","id":1,"FULLNAME":"Johny Cage"}}, status: Success]
Any help or suggestion is highly appreciated.
Check your return data from web-service. I think you are converting it in Jason String multiple times, Or something like this. There is no issue in above code. Check your server side.

Swift in Xcode 6: How to use geocoding properly with Google Maps?

I'm new to swift. I am trying to create a call to Google's API to convert any inputted addresses to a long, lat location on google maps, using their sdk.
I thought it'd be easier to start by following a tutorial http://www.appcoda.com/google-maps-api-tutorial/, then dissecting it. But I cannot seem to get it this particular line working. It will come out with a "error-exc-bad-instruction-code-exc-i386-invop-subcode-0x0" on the dicitonary line. I read other sample work on reverse geocoding that are to date, and they look very similar, but none are working. What am I doing wrong?
let dictionary: Dictionary<NSObject, AnyObject> =
NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options:
NSJSONReadingOptions.MutableContainers, error: &error) as!
Dictionary<NSObject, AnyObject>
Full function below:
func geocodeAddress(address: String!, withCompletionHandler completionHandler: ((status: String, success: Bool) -> Void)) {
if let lookupAddress = address {
var geocodeURLString = baseURLGeocode + "address=" + lookupAddress
geocodeURLString = geocodeURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let geocodeURL = NSURL(string: geocodeURLString)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let geocodingResultsData = NSData(contentsOfURL: geocodeURL!)
var error: NSError?
let dictionary: Dictionary<NSObject, AnyObject> = NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! Dictionary<NSObject, AnyObject>
// let dictionary: Dictionary = NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! Dictionary
if (error != nil) {
println(error)
completionHandler(status: "", success: false)
}
else {
// Get the response status.
let status = dictionary["status"] as! String
if status == "OK" {
let allResults = dictionary["results"] as! Array<Dictionary<NSObject, AnyObject>>
self.lookupAddressResults = allResults[0]
// Keep the most important values.
self.fetchedFormattedAddress = self.lookupAddressResults["formatted_address"] as! String
let geometry = self.lookupAddressResults["geometry"] as! Dictionary<NSObject, AnyObject>
self.fetchedAddressLongitude = ((geometry["location"] as! Dictionary<NSObject, AnyObject>)["lng"] as! NSNumber).doubleValue
self.fetchedAddressLatitude = ((geometry["location"] as! Dictionary<NSObject, AnyObject>)["lat"] as! NSNumber).doubleValue
completionHandler(status: status, success: true)
}
else {
completionHandler(status: status, success: false)
}
}
})
}
else {
completionHandler(status: "No valid address.", success: false)
}
}
For Swift 2, this can be used:
First, declare your variable as an empty dictionary outside of the do-catch block and do the assignment in the block, like below
do {
dictionary = try NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<NSObject, AnyObject>
} catch {
//something
}

Xcode 6.3.1 Swift 1.2 library wherekey can't be invoked

Recently note that wherekey on PFQuery does not work. I tried 3 approaches but all failed. I am using parse-library-1.7.2 on Xcode 6.3.
Error for approach1: Cannot invoke 'whereKey' with an argument list of type '(String, AnyObject)'
Error for approach2: 'String?'is not convertible to 'StringLiteralConvertible'
Error for approach3: 'AnyObject?' is not convertible to 'String'
Code is as below. Anyone can help with this please? Thanks in advance.
// Define the query that will provide the data for the table view
class MyController: PFQueryTableViewController {
override func queryForTable() -> PFQuery {
var query = PFQuery(className: "Ticket")
//Approach 1
query.whereKey(sellerIdKey, equalTo: currentPhoneUser["objectId"]!)
//Approach 2
if let sellerId = currentPhoneUser["objectId"] as? String {
query.whereKey(sellerIdKey, equalTo: sellerId)
query.orderByDescending("createdAt")
return query
} else {
fatalError("Can't get Object Id of this user")
}
//Approach 3
if let sellerId = currentPhoneUser["objectId"] as! String {
query.whereKey(sellerIdKey, equalTo: sellerId)
query.orderByDescending("createdAt")
return query
} else {
fatalError("Can't get Object Id of this user")
}
}
}
Turns out to be a swift 1.2 issue.
How to cast AnyObject? to String in Swift 1.2
Below is my final solution that compiles:
override func queryForTable() -> PFQuery {
var query = PFQuery(className: "Ticket")
let objectId = currentPhoneUser?["objectId"] as? String
if let constObjectId = objectId {
query.whereKey(sellerIdKey, equalTo: constObjectId)
} else {
fatalError("Cannot find Object Id of current user")
}
return query
}

Swift Parse.com unable to retrieve object

So I am trying to get a String that is saved within an object from Parse.com. Here is the code that I am using to do so:
var query: PFQuery = PFQuery(className: "Replys")
query.getObjectInBackgroundWithId("ipmdKB0N1N") {
(object: PFObject?, error: NSError?) -> Void in
if error == nil && object != nil {
println(object)
self.replyField.text = object["Replys"]
} else {
println(error)
}
}
I want to make this string the text of the label called "replyField" but when I try to do that, Xcode gives an error like "Cannot assign value "AnyObject?" to type "String?"" Even when I add as! String, it still gives a similar (though not exactly the same) error. Any ideas why?
You should unwrap optional of object. Such as object!["Replys"] or object?["Replys"]
Like below:
self.replyField.text = object!["Replys"] as! String
or
self.replyField.text = object?["Replys"] as! String
let replysString = object["Replys"] as! NSString
self.replyField.text = replysString as String

Type 'String' does not confirm to protocol 'NSCopying' with NSDictionary

I'm trying to use the Google Geolocation api, within Xcode using Swift, to allow the conversion of text address to latitude and longitude.
http://maps.googleapis.com/maps/api/geocode/json?address=washington%20dc is an example JSON call.
the error: Type 'String' does not confirm to protocol 'NSCopying', appears when trying to access elements within the dictionary of results.
#IBAction func submitButtonPressed(sender: AnyObject) {
var address = addAddressTextField.text
var escapedAddress = address.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let urlpath = "http://maps.googleapis.com/maps/api/geocode/json?address=" + escapedAddress!
println(urlpath)
let url = NSURL(string: urlpath)!
let urlSession = NSURLSession.sharedSession()
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { (data, responce, error) -> Void in
if error != nil{
println("there is an error")
}
var err : NSError?
var results = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if err != nil{
println("there is a second error")
}
let formattedAddress: AnyObject! = results["results"]![0]!["formatted_address"]!
let latitude: AnyObject! = results["results"]![0]!["geometry"]!["location"]!["lat"]!
let longitude: AnyObject! = results["results"]![0]!["geometry"]!["location"]!["lng"]!
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.fullAddressLabel.text = "\(formattedAddress)"
self.latLabel.text = "\(latitude)"
self.longLabel.text = "\(longitude)"
})
})
jsonQuery.resume()
}
The error only occurs on the lines:
let latitude: AnyObject! = results["results"]![0]!["geometry"]!["location"]!["lat"]!
let longitude: AnyObject! = results["results"]![0]!["geometry"]!["location"]!["lng"]!
and the let formattedAddress: AnyObject! = ... line works perfectly.
I have tried defining the variables as Strings and NSStrings and using '... as String' within the definition but to no luck.
The problem is not the returned variables but the keys. NSDictionary expects its keys to conform to NSCopying and presumably a Swift string literal does not.
I would try to figure out exactly which access is causing the issue by not trying to get the whole thing in one line (your program will crash btw if you get an unexpected response because you assume all the keys exist in all the dictionaries).
On the assumption that you know you have at least one result and you have put it in a variable called results0 (this comes from external data so you must check it), I'd do this
var latitude: Double?
var longitude: Double?
if let geometry = results0["geometry"] as? NSDictionary
{
if let location = geometry["location"] as? NSDictionary
{
latitude = location["lat"] as? Double
longitude = location["lon"] as? Double
}
}
Either you will get the same error on one of the lines accessing the dictionaries or something else may go wrong. You might have to fiddle about with the casting too to get it right (I haven't even tried to compile the above code). But the point is that now the code is spread out over several lines, it should be much easier to isolate the error.
I ran into the same issue with json try this
let latitude = results["results"]![0]!["geometry"]!!["location"]!!["lat"]!! as String
let longitude = results["results"]![0]!["geometry"]!!["location"]!!["lng"]!! as String
note, This does not include any error checking at all also if the labels you are updating are standard labels you can just do
mylabel.stringValue = latitude
or something like that :P
Here is a direct copy of how i phrase my json objects without error checking
var FilePath = object["main"]![row]!["Paths:"]!!["FilePath:"]!! as String

Resources