[英]How to receive String Array from Parse Cloud Code in Swift?
I've written a Parse cloud code function which returns some data from the database. 我编写了一个Parse云代码函数,该函数从数据库返回一些数据。 I see those in the "response" when I do a println in XCode.
当我在XCode中执行println时,我会在“响应”中看到这些内容。 It looks like it's wrapped in a double optional!?
看起来好像包裹在一个double可选中! What I'm making wrong in the
if let
and in the for
loop? 我在
if let
和for
循环中出错了吗? How do I get (unwrap) a String Array out of it? 我如何从中获取(解包)字符串数组?
My code in Swift: 我在Swift中的代码:
PFCloud.callFunctionInBackground("TopTwo", withParameters: ["rating":5]) {
(response: AnyObject?, error: NSError?) -> Void in
if error == nil {
println("Successfully retrieved \(response!.count) scores.")
println("Here are the flower names: \(response)")
if let objects = response as? [PFObject] {
for object in objects {
println(object.objectId)
}
}
} else {
println("Error: \(error!) \(error!.userInfo!)")
}
}
What I see in the console: 我在控制台中看到的是:
Successfully retrieved 2 scores.
Here are the flower names: Optional((
rose,
"sunflower"
))
Maybe there is also an error in my cloude code. 也许我的cloude代码中也有错误。 Here you can see what I've done:
在这里,您可以看到我做了什么:
Parse.Cloud.define("TopTwo", function(request, response) {
var query = new Parse.Query("Flowers");
console.error("Get flowers with the rating: " + request.params.rating);
query.equalTo("stars", request.params.rating);
query.find({
success: function(results) {
console.error("Results: " + results);
var list = [];
for (i = 0; i < results.length; i++) {
list[i] = results[i].get('flowerName');
}
console.error("Flower name list: " + list);
response.success(list);
},
error: function() {
response.error("lookup failed");
}
});
});
And here the parse logs: 这是解析日志:
Results: [object Object],[object Object]
Flower name list: rose,sunflower
(I'm using XCode 6.3.2 - Swift 1.2) (我正在使用XCode 6.3.2-Swift 1.2)
Many thanks in advance! 提前谢谢了!
Okay, I could solve it on my own. 好吧,我可以自己解决。
The object which is returned from cloud code is already an Array. 从云代码返回的对象已经是一个数组。 Therefore a casting into
NSArray
has to be made instead of a casting into [PFObject]
. 因此,必须强制转换为
NSArray
而不是强制转换为[PFObject]
。
Here is the working Swift code: 这是有效的Swift代码:
PFCloud.callFunctionInBackground("dayTopFive", withParameters: ["day":1]) {
(response: AnyObject?, error: NSError?) -> Void in
if error == nil {
println("Successfully retrieved \(response!.count) scores.")
// This is working:
let objects = response as! NSArray
for object in objects {
println("A top flower is: \(object)")
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.