Parse: Saving data to the main "User" class - parse-platform

I just have basic code for testing purposes.
let user = PFObject(className: "User")
user["email"] = userEmail
user.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
....
}
But I always get this result.
Is the main User class named differently?

You should be using PFUser rather than creating a PFObject with the classname of "User"
let user = PFUser()
user["email"] = userEmail
user.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
...
}

Related

Local Parse Database gives error in SwiftUI

I'm trying to store objects in a local Parse datastore on the device itself. I get an error when retrieving the stored object: 'Method requires Pinning enabled.'
I've implemented 'Parse.enalbelLocalDatastore() in AppDelegate.swift. I tried to hard-code the object to be sure there was an object to retrieve.
let configuration = ParseClientConfiguration
{
$0.applicationId = "..."
$0.clientKey = "..."
$0.server = "..."
}
Parse.enableLocalDatastore()
Parse.initialize(with: configuration)
...
func blancoUser() {
let object = PFObject(className: "UserData")
object["id"] = (UUID().uuidString)
object["LoginName"] = "userName"
object["PinCode"] = "00000"
object["ScreenName"] = "test"
object["YearOfBirth"] = 0
object.pinInBackground()
}
...
let query = PFQuery(className: "UserData")
var users:[UserData] = [UserData]()
query.fromLocalDatastore()
query.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
if let error = error {
print(error.localizedDescription)
} else if let objects = objects
I want to get the variable 'users' with the locally stored user objects. What am I missing? Or does the ParseLocalDatastore work differently in SwiftUI.
Can you try to initialize the SDK like this?
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let parseConfig = ParseClientConfiguration {
$0.isLocalDatastoreEnabled = true
$0.applicationId = parseApplicationId
$0.clientKey = parseClientKey
$0.server = parseServerUrlString
}
Parse.initialize(with: parseConfig)
}
}
Reference: https://docs.parseplatform.org/ios/guide/#local-datastore

Swift 3 - Invalid conversion from throwing function type '(Any) -> Void'

I'm new to swift and
I'm not understanding why I'm getting this error.
I've being reading similar questions and so far none of them solved this error or I have not found it:
Invalid conversion from throwing function of type '(_) throws -> ()'
to non-throwing function type '(Any) -> ()'
At the line:
self.ws.event.message = { message in
The piece of code with the error:
public var ws = WebSocket()
public func websocket(token: Any){
self.ws.open("ws://"+String(APIHOST)+":"+String(port)+"/ws?token="+String(describing: token))
self.ws.event.message = { message in
if let text = message as? String {
let json = try JSONSerialization.jsonObject(with: text, options: []) as? [String: Any]
print("recv: \(text)")
}
}
}
Thanks for any help
Try below piece of code
public var ws = WebSocket()
public func websocket(token: Any){
self.ws.open("ws://"+String(APIHOST)+":"+String(port)+"/ws?token="+String(describing: token))
self.ws.event.message = { message in
if let dataObj = message as? Data {
do {
let json = try JSONSerialization.jsonObject(with:dataObj, options: []) as? [String: Any]
print("recv: \(text)")
} catch error {
print("Unable to load data: \(error)")
}
}
}
}
If you have a function that throws something, it usually means there might be a chance of error when accessing that data in your case JSON.
If function throws you need to do {} catch {} to tell Swift you are going to handle an error.

Xcode 7 Error Code "Cannot convert value type([AnyObject]

Heres a copy of my code where the error is giving me, the error is on the line where it says query.findobjectsInBackgroundWithBlock. The full error message is this: `Cannot convert value type ([AnyObject]!, NSError!) -> Void to expected argument type 'PFQueryArrayResultBlock?'
// Retrieve Messages
func retrieveMessages() {
// Create a new PFQuery
var query:PFQuery = PFQuery(className: "Message")
// Call findobjectsinbackground
query.findObjectsInBackgroundWithBlock {(objects:[AnyObject]!, error:NSError!) -> Void in
// Clear the messagesArray
self.messageArray = [String]()
// Loops through the objects
for messageObject in objects {
// Retrieve the text column value of each PFObject
let messageText:String? = (messageObject as! PFObject)["Text"] as? String
// Assign it into our messagesArray
if messageText != nil {
self.messageArray.append(messageText!)
}
}
// Reload the tableview
self.messageTableView.reloadData()
}
}
The method signature had improved in Swift 2.0 with Parse SDK 1.10.0. Replace [AnyObject]! with [PFObject]?. [PFObject] is an optional because Swift doesn't know if it will exist or not.
func retrieveMessages() {
var query:PFQuery = PFQuery(className: "Message")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
self.messageArray = [String]()
for messageObject in objects {
let messageText:String? = (messageObject as! PFObject)["Text"] as? String
if messageText != nil {
self.messageArray.append(messageText!)
}
}
self.messageTableView.reloadData()
}
}

Parse query equalto PFUser Object

This is what I have pulled from the PFUser:
let currentUser = PFUser.currentUser()
currentUser!.refreshInBackgroundWithBlock { (object, error) -> Void in
print("Refreshed")
currentUser!.fetchIfNeededInBackgroundWithBlock { (result, error) -> Void in
let userSchool = currentUser!.objectForKey("school") as! String
And then I want to use the "userSchool" in a Query for Participants.
var query = PFQuery(className:"Participant")
query.whereKey("school", equalTo:userSchool)
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
}
How do I get the equalTo: to signify "userschool" so I can then pull the data?
This is all on the same table too, BTW.

Closure is not constructible with

I am practicing Swift and I have the following code:
import Foundation
#objc class Model {
typealias completionBlock = (data: NSData?, error: NSError?) -> Void
func saveEmailAccount(email: String, password: String, mailServer: String, mailPort: Int, completionHandler: completionBlock) -> Void {
let httpPOSTBody = ["email" : email, "password" : password, "mailServer" : mailServer, "mailPort" : mailPort]
let urlRequest = NSMutableURLRequest()
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.HTTPMethod = "POST"
urlRequest.HTTPBody = NSJSONSerialization.dataWithJSONObject(httpPOSTBody, options: nil, error: nil)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
session.dataTaskWithURL(urlRequest.URL!, completionHandler: { (data: NSData!, response:NSURLResponse!, error: NSError!) -> Void in
completionBlock(data, error)
})
}
}
But I am getting "completionBlock is not constructible with '(NSData!, NSError!)'. Not sure what I'm doing wrong
You're trying to invoke completionHandler with the typo completionBlock Change the block invocation from:
completionBlock(data, error)
to:
completionHandler(data, error)
One reason why Apple suggests (and I concur) that type names should start with caps and variable names with lower case.
The other problem is that by defining the type alias as:
typealias completionBlock = (data: NSData?, error: NSError?) -> Void
You are specifying that the completion block should be defined and called with named parameters:
completionHandler(data:data, error:error)
Or, change the type alias to:
typealias completionBlock = (NSData?, NSError?) -> Void
Which would be more inline with the norms I've seen.

Resources