Getting this error when trying to implement Chartboost on Swift xcode? - xcode

I have this code to add my AppID and App Signature to my AppDelegate.swift file but I get an error on the last line of code. It says: "Cannot invoke startWithAppId with an argument list of type (String, String, Delegate: AppDelegate). What am I doing wrong? Thanks!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let kChartboostAppID = "5236547547457856858568"
let kChartboostAppSignature = "523525225"
Chartboost.startWithAppId(kChartboostAppID, appSignature: kChartboostAppSignature, delegate: self)
}

I forgot to add the ChartboostDelegate initializer. It works now!

Related

Cannot convert value of type 'NSData' to expected argument type 'String'

I'm writing codes on swift in XCode. This is the code:
import UIKit
import Foundation
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let notificationTypes : UIUserNotificationType = [.Alert, .Badge, .Sound]
let notificationSettings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
return true
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings)
{
UIApplication.sharedApplication().registerForRemoteNotifications()
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
print("TOKEN:", deviceToken);
let token = String(data: deviceToken, encoding: NSUTF8StringEncoding);
let myUrl = NSURL(fileURLWithPath: "http://......php?id=" + token);
print("URL:",fileURLWithPath: "http://......php?id=" + token);
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print(error.localizedDescription)
}
/* func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
}*/
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
Compiler gives me an error on the func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {" and it says me "Cannot convert value of type 'NSData' to expected argument type 'String'"... but I can't understand the way to solve the problem. So, can somebody help me to correct the error?
var charSet: NSCharacterSet = NSCharacterSet(charactersInString: "<>")
var tokenStr: String = (deviceToken.description as NSString)
.stringByTrimmingCharactersInSet(characterSet)
.stringByReplacingOccurrencesOfString( " ", withString: "") as String
print(deviceTokenString)
Try that
USe this, for sending token to the server. Worked well for me
var token: String = "\(deviceToken)"
let rawtoken = token.stringByReplacingOccurrencesOfString(">", withString: "")
let cleantoken = rawtoken.stringByReplacingOccurrencesOfString("<", withString: "")
var finaltoken = cleantoken.stringByReplacingOccurrencesOfString(" ", withString: "")
Final token is the one that you are supposed to use.
Source was Udemy online courses.
Note that the token is BINARY, so you cannot easily convert it to a string (no UTF8!).
It is a good practice to convert it to hex:
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for var i = 0; i < deviceToken.length; i++ {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
print("Push token: \(tokenString)")

Swift + Parse Logout Error

I have an error when trying to kill user session when the logout button is pressed. Anybody have an idea where im going wrong? Thanks in advance
Here is the code
#IBAction func logoutButtonTapped(sender: AnyObject) {
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "isUserLoggedIn");
NSUserDefaults.standardUserDefaults().synchronize();
PFUser.logOutInBackgroundWithBlock({ (error:NSError!) -> Void in
self.performSegueWithIdentifier("loginView", sender: self);
})
Error: 'Cannot invoke 'logOutInBackgroundWithBlock' with an argument list of type '((NSError) -> Void)'
Remove the type specifier NSError! from the param.
PFUser.logOutInBackgroundWithBlock({(error) -> Void in
self.performSegueWithIdentifier("loginView", sender: self);
})

how to use local datastore to save and query data with parse and swift

In my app. There will be user list and message list as my code below
message list code (load the list from parse)
#IBOutlet var messageTableView: UITableView!
var messageArray:[String] = ["Lope"]
override func viewDidLoad() {
super.viewDidLoad()
retrieveMessages()
}
func retrieveMessages() {
var query = PFQuery(className:"Messages")
var user = PFUser.currentUser()
query.whereKey("user", equalTo:user.objectId)
query.findObjectsInBackgroundWithBlock { [weak self]
(objects:[AnyObject]?, error:NSError?) -> Void in
println(objects)
println("succeed")
let messages = objects
for object in objects!{
if let message = object["messageTextColumn"] as? String {
println(object)
self?.messageArray.append(message)
}
}
self?.tableView.reloadData()
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messageArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("messageCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = messageArray[indexPath.row]
return cell
}
add message code (add new message to parse)
class addMessageViewController: UIViewController {
#IBOutlet weak var addMessageText: UITextField!
#IBAction func addMessage(sender: AnyObject) {
var newMessage = addMessageText.text
let message = PFObject(className: "Messages")
var user = PFUser.currentUser()
message["messageTextColumn"] = newMessage
message["user"] = user.objectId
message.saveInBackgroundWithBlock {(success: Bool, error: NSError?) -> Void in
if (success) {
println("added to Message Class")
println(user)
message.saveInBackground()
} else {
// Error saving message
}
}
}
I want to use parse local datastore to store these data in my app locally so that my app won't have to use the internet connect all the time and when the user is not connect to the internet the user list and message list will still appear.
The problem is I don't know what method in local datastore should I use where should I put the local datastore code in "add message code" to save the new message and in "message list code" to query it to my app locally and if there's any update, It will do later after our local "message list" has been loaded. Any help is appreciated.
Thanks!
To begin with Parse data store, you need to opt in from your app delegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// Opt in for Parse Local data store *Before Parse.setApplicationId*
Parse.enableLocalDatastore()
Parse.setApplicationId("YOUR PARSE APP ID",
clientKey: "YOUR PARSE CLIENT ID")
//... other code that you might need when app did finish launching
return true
}
Later when you save a new message you will use:
message.saveEventually()
This will save in the local data store, and eventually (when internet will be available) in the remote data store.
From here you might also be interested in the use of Parse data pinning.
See Parse doc for more.
Hope this helps

Apple - Provisioning profile + Push Notifications

I followed the guide on Parse.com on how to create a certificate and prepare a provisioning account to accept Push Notifications. When i go to Preferences/Accounts :
It shows on the bottom, but when i try to choose it from the Build Settings Tab, it doesn't show, and i always get this error : "no valid 'aps-environment' entitlement string found for application"
I tried this from scratch several times, using several Xcode & parse Apps, Please help me.
Appdelegate code :
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Parse.setApplicationId("MyAppId", clientKey: "MyAppClientKey")
var notificationType: UIUserNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
var settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationType, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
var currentInstallation: PFInstallation = PFInstallation()
currentInstallation.setDeviceTokenFromData(deviceToken)
currentInstallation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println(error.localizedDescription)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
}
Have you added the device onto the Development Provisioning Profile, then download and installed it? I got that same error until the device was added.

Xcode , Parse.com - Push notifications don't show on my phone.

followed the guide on Parse.com on how to create a certificate and prepare a provisioning account to accept Push Notifications. When i go to Preferences/Accounts : It shows on the bottom, but when i try to choose it from the Build Settings Tab, it doesn't show, and i always get this error : "no valid 'aps-environment' entitlement string found for application"
My phone is recognised by the Parse app, and it sends notifications successfully, but my phone never receives them. I tried this from scratch several times, using several Xcode & Parse Apps.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Parse.setApplicationId("MyAppId", clientKey: "MyAppClientKey")
var notificationType: UIUserNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
var settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationType, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
var currentInstallation: PFInstallation = PFInstallation()
currentInstallation.setDeviceTokenFromData(deviceToken)
currentInstallation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println(error.localizedDescription)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
}
1) Did you allow push notifications from your app project?
2) Do you have the correct build identifiers set in parse and in your app?
I have another delegate method that I don't see in your post.
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings!)
{
UIApplication.sharedApplication().registerForRemoteNotifications()
}

Resources