siegesmund / SwiftDDP

A Meteor client, written in Swift
MIT License
145 stars 60 forks source link

Invalid type in JSON write when "Call" with a Object #15

Closed Sadmansamee closed 8 years ago

Sadmansamee commented 8 years ago

I'm calling a function on server , call looks likes this

Meteor.call("addCustomerAddress", params: [self.currentDeliveryAddress]) 
{ result, error in
}

and Class is like this

class CurrentDeliveryAddress
{
    var streetName: String!
    var areaName: String!
    var buildingName: String!
    var apartmentName: String!
    var locationName: String!
    var cityName: String!
    var phoneNumber: String!
    var location: Location!
    var areaId: String!

    class Location 
    {
        var lat : Double!
        var lng : Double!

        init(lat:Double,lng :Double)
        {
            self.lat = lat
            self.lng = lng
        }
    }
}

and Function on server side is like

addCustomerAddress: function (data) {
        try {
            check(data, {
                streetName: String,
                areaName: String,
                buildingName: String,
                apartmentName: String,
                locationName: String,
                cityName: String,
                phoneNumber: String,
                location: {
                    lat: Number,
                    lng: Number
                },
                areaId: String
            });
​
            data.id = Random.id();
            var isUpdate = Meteor.users.update(this.userId, {
                $push: {'profile.address': data}
            }, {upsert: false});
​
            if (isUpdate) {
                logger.info('platform', 'user address added: ' + data);
                return isUpdate;
            }
​
        } catch (e) {
            logger.error('platform', 'unable to add customer address: ' + e);
            throw new Meteor.Error(403, e.message);
        }
    }

when ever I'm calling this i'm getting this error "Terminating app due to uncaught exception

NSInvalidArgumentException', reason: 'Invalid type in JSON write

What could be the issue?

siegesmund commented 8 years ago

This is covered in the docs here.

Your object is not serializable by NSJSONSerialization, and arguments passed to Meteor.call must be serializable by NSJSONSerialization. See here for more info on NSJSONSerialization.

The short answer is, pass a dictionary of your CurrentDeliveryAddress instance properties, instead of the instance itself.

Sadmansamee commented 8 years ago

Now I'm using

let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(self.currentDeliveryAddress, options: []) as! NSDictionary And

class CurrentDeliveryAddress : NSData

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -bytes only defined for abstract class. Define -[UrbanChef.CurrentDeliveryAddress bytes]!' also tried with SwiftyJson

let swiftyJson = JSON(data: self.currentDeliveryAddress) Same error