在Xcode中调用一个函数

时间:2015-11-08 02:53:51

标签: xcode swift parse-platform

我的Parse数据库中有Inventory表,有两个相关字段我怎样才能用swift做到这一点?我使用Js创建云代码

Parse.Cloud.define("retrieveproducts", function(request, response) {
  var productDictionary ={};
  var query = new Parse.Query("Post");
  query.each(
     function(result){
        var num = result.get("quantity");
        if(result.get("productid") in productDictionary){
             productDictionary[result.get("productid")] += num;
        }
        else{
             productDictionary[result.get("productid")] = num;
        }
    }, {
        success: function() {
            response.success(productDictionary);
        },
        error: function(error) {
            response.error("Query failed. Error = " + error.message);
        }
    });
});

我想调用此函数:但是通过此调用调用它时遇到了一些麻烦

let params = ["productid": String(), "string": String()]
  
PFCloud.callFunctionInBackground("retrieveproducts", withParameters: params) {
            (ratings, error) in
            if (error == nil) {
                print("\(params)")
            }
        }

1 个答案:

答案 0 :(得分:0)

Swift Code

let reportedId = "someUsersObjectId"
    PFCloud.callFunctionInBackground("suspendUser", withParameters: ["userId": reportedId]) {
                            (result, error) in
                            if (error == nil) {
                                print(result)
                            }
                        }

Cloud Code:

  Parse.Cloud.define("suspendUser", function(request, response) {
      Parse.Cloud.useMasterKey()
      //var User = Parse.Object.extend(Parse.User);
        //var user = new User();
        //user.id = request.params.userId;
        user = new Parse.User({id:request.params.userId})
        user.fetch().then(function() {
                user.set("suspended", true)
                user.save().then(function(newMostRecentAgain) {
                    response.success("Cloud code called! " + request.params.userId)
                  }, function(error) {
                  // The save failed.  Error is an instance of Parse.Error.
                  })
            });
      });

让我带您了解这里发生的事情,这样您就可以更好地弄清楚如何编写代码(因为我无法确切地知道您想做什么)。

1:在我的Swift代码中,withParameters是您将信息传递给云代码的方式,它采用字典的风格。在这里,我传递的用户是我想报告的objectId。

PFCloud.callFunctionInBackground("suspendUser", withParameters: ["userId": reportedId]) {

2:在我的Cloud代码中,我得到了我用objectId报告的用户的Parse对象,我正在使用params。由于您无法将整个对象传递给云代码,因此我使用您看到的objectId和user.Fetch()重建对象。

user = new Parse.User({id:request.params.userId})

3:在我的Cloud代码中,在我更改了“暂停”的值后成功保存用户后,我将一个字符串发送回IOS用户。

response.success("Cloud code called! " + request.params.userId)

4:最后,在我的Swift Code中,然后我从成功打印返回的字符串

print(result)

这会让事情变得更清楚吗?如果有什么事情没有意义,请告诉我。