сохранение объектов для разбора

Я все еще новичок в разработке ios, но у меня есть хорошее знание языка Swift, сейчас я пытаюсь научиться сохранять объекты в Parse после того, как я создал свое приложение в Parse и загрузил шаблон xcode swift из Parse и вставил идентификатор приложения и ключ cleint в файл appDelegate.swift и добавьте код файла сохранения из Parse в файл viewController и попытался запустить приложение, я получил эту ошибку в appDelegate.swift: пожалуйста, проверьте ссылку ниже, чтобы просмотреть ошибку: 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())
    // }
}

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

и для viewController.swift я использовал этот код:

импортировать UIKit импортировать синтаксический анализ

класс 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.
}

}


person Alialhakeem    schedule 25.04.2015    source источник


Ответы (1)


У Parse очень хорошая документация, и здесь вы можете узнать, как сохранять объекты . Просто переключите язык программирования на Swift.

Что касается ошибки, которую вы получаете, кажется, что у вас есть дополнительный параметр. Если вы хотите обработать ответ с помощью блока, вы должны использовать этот метод: + subscribeToChannelInBackground:block:. Для справки вы можете прочитать документацию< /а>.

EDIT: Попробуйте использовать NSError? вместо NSError!. Итак, у вас должно быть что-то вроде этого:

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)
        }
    })
person Vasil Garov    schedule 25.04.2015
comment
Я все это сделал, но как только я запускаю приложение, я получаю эту ошибку! Зачем это ради бога? - person Alialhakeem; 25.04.2015
comment
не могли бы вы отредактировать свой пост и обновить код, чтобы мы могли знать, что происходит - person Vasil Garov; 25.04.2015
comment
Это действительно делает работу! Но почему они не меняют его в xcode с ! к ? , Еще одна вещь, которая не работала здесь полностью. Когда я запускал приложение и перешел к ядру приложения для синтаксического анализа, я не смог найти там сохраненных значений! почему это ? Изменяет ли ! к ? влияет на это? - person Alialhakeem; 26.04.2015
comment
Метка ? означает, что ваш параметр error имеет необязательный тип и не имеет ничего общего с Parse. Чтобы выяснить, почему ваш код не вставляет никаких значений в Parse, вы должны сначала установить точку останова в gameScore.saveInBackgroundWithBlock и посмотреть, идет ли она туда. - person Vasil Garov; 26.04.2015
comment
Теперь, когда я запускаю приложение, я получаю эту ошибку: Делегат приложения должен реализовать свойство окна, если он хочет использовать основной файл раскадровки. Push-уведомления не поддерживаются в симуляторе iOS. - person Alialhakeem; 26.04.2015