0

I'm still new to ios development but I have a good knowledge of the swift language, I'm trying now to learn how to save objects to Parse, after I created my app on parse and downloaded the xcode swift template from Parse and pasted the application id & cleint-key to the appDelegate.swift file and add save file code from Parse to the viewController file and tried to run the app, I got this error in appDelegate.swift : please check the link below to view the error: http://i.gyazo.com/9ef2283ab1db616d4f8a13350482cbfd.png

//
//  AppDelegate.swift
//
//  Copyright 2011-present Parse Inc. All rights reserved.
//

import UIKit

import Bolts
import Parse

// If you want to use any of the UI components, uncomment this line
// import ParseUI

// If you want to use Crash Reporting - uncomment this line
// import ParseCrashReporting

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    //--------------------------------------
    // MARK: - UIApplicationDelegate
    //--------------------------------------

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        Parse.setApplicationId("S4EvMUoPTDRwK7cxkfgfgAX09VBDcWOwx1V51WCd",
            clientKey: "y7vxfm1q4BORIa599StUCnCIfghGiOoekbUn7N00")

        Parse.enableLocalDatastore()

        // ****************************************************************************
        // Uncomment this line if you want to enable Crash Reporting
        // ParseCrashReporting.enable()
        //
        // Uncomment and fill in with your Parse credentials:
        // Parse.setApplicationId("your_application_id", clientKey: "your_client_key")
        //
        // If you are using Facebook, uncomment and add your FacebookAppID to your bundle's plist as
        // described here: https://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/
        // Uncomment the line inside ParseStartProject-Bridging-Header and the following line here:
        // PFFacebookUtils.initializeFacebook()
        // ****************************************************************************

        PFUser.enableAutomaticUser()

        let defaultACL = PFACL();

        // If you would like all objects to be private by default, remove this line.
        defaultACL.setPublicReadAccess(true)

        PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser:true)

        if application.applicationState != UIApplicationState.Background {
            // Track an app open here if we launch with a push, unless
            // "content_available" was used to trigger a background push (introduced in iOS 7).
            // In that case, we skip tracking here to avoid double counting the app-open.

            let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
            let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
            var noPushPayload = false;
            if let options = launchOptions {
                noPushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil;
            }
            if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {
                PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
            }
        }
        if application.respondsToSelector("registerUserNotificationSettings:") {
            let userNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
            let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
            application.registerUserNotificationSettings(settings)
            application.registerForRemoteNotifications()
        } else {
            let types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Alert | UIRemoteNotificationType.Sound
            application.registerForRemoteNotificationTypes(types)
        }

        return true
    }

    //--------------------------------------
    // MARK: Push Notifications
    //--------------------------------------

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        let installation = PFInstallation.currentInstallation()
        installation.setDeviceTokenFromData(deviceToken)
        installation.saveInBackground()

        PFPush.subscribeToChannelInBackground("", block: { (succeeded: Bool, error: NSError!) -> Void in
            if succeeded {
                println("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.");
            } else {
                println("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %@.", error)
            }
        })
    }

    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        if error.code == 3010 {
            println("Push notifications are not supported in the iOS Simulator.")
        } else {
            println("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)
        }
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
        PFPush.handlePush(userInfo)
        if application.applicationState == UIApplicationState.Inactive {
            PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
        }
    }

    ///////////////////////////////////////////////////////////
    // Uncomment this method if you want to use Push Notifications with Background App Refresh
    ///////////////////////////////////////////////////////////
    // func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    //     if application.applicationState == UIApplicationState.Inactive {
    //         PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
    //     }
    // }

    //--------------------------------------
    // MARK: Facebook SDK Integration
    //--------------------------------------

    ///////////////////////////////////////////////////////////
    // Uncomment this method if you are using Facebook
    ///////////////////////////////////////////////////////////
    // func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
    //     return FBAppCall.handleOpenURL(url, sourceApplication:sourceApplication, session:PFFacebookUtils.session())
    // }
}

//************************

and for the viewController.swift I used this code :

import UIKit import Parse

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()


    var gameScore = PFObject(className:"GameScore")
    gameScore["score"] = 1337
    gameScore["playerName"] = "Sean Plott"
    gameScore["cheatMode"] = false
    gameScore.saveInBackgroundWithBlock {
        (success: Bool, error: NSError?) -> Void in
        if (success) {
            // The object has been saved.
        } else {
            // There was a problem, check error.description
        }
    }

}



 override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

Alialhakeem
  • 1
  • 1
  • 1
  • 5

1 Answers1

0

Parse has a really good documentation and here you can find how to save objects. Just switch the programming language to Swift.

As for the error you are getting it seems that you have an extra parameter. If you want to handle the response with a block you should be using this method: + subscribeToChannelInBackground:block:. For reference you can read the documentation.

EDIT: Try with NSError? instead of NSError!. So you should have something like this:

PFPush.subscribeToChannelInBackground("", block: { (succeeded: Bool, error: NSError?) -> Void in
        if succeeded {
            println("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.");
        } else {
            println("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %@.", error)
        }
    })
Vasil Garov
  • 4,851
  • 1
  • 26
  • 37
  • I did all that, but as soon as I run the app I get that error ! Why is that for god's sake? – Alialhakeem Apr 25 '15 at 17:05
  • could you edit your post and update the code so we can know what is going on – Vasil Garov Apr 25 '15 at 17:25
  • That does the job indeed ! But why they don't change it in xcode from ! to ? , One more thing that didn't work fully here, Is when I run the app and went to my app core in parse I couldn't find any saved values in there ! why is that ? Does changing the ! to ? has effect on that ? – Alialhakeem Apr 26 '15 at 12:31
  • The `?` mark means that your `error` parameter is of optional type and has nothing to do with Parse. To find out why your code isn't inserting any values to Parse you should first set a break point in `gameScore.saveInBackgroundWithBlock` and see if it goes there. – Vasil Garov Apr 26 '15 at 16:04
  • Now when I run the app, I get this error : " The app delegate must implement the window property if it wants to use a main storyboard file. Push notifications are not supported in the iOS Simulator." – Alialhakeem Apr 26 '15 at 19:25