parse - swift unauthorized error - ios

I'm new to iOS software development and swift and I'd like to make an app that is similar to instagram. For this I created a VM instance in google cloud with the Network tags parse-1-tcp-443, parse-1-tcp-80. I ran the code above in the newest version of xcode and got those errors. Why do I get unauthorized error when after logging in username, password url are correct?
Allow Arbitrary Loads is set to yes in info.plist
Thanks in advance!
import UIKit
import Parse
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.enableLocalDatastore()
let parseConfiguration = ParseClientConfiguration(block: { (ParseMutableClientConfiguration) -> Void in
ParseMutableClientConfiguration.applicationId = "user"
ParseMutableClientConfiguration.clientKey = "*********"
ParseMutableClientConfiguration.server = "http://35.19.10.151/parse"
})
Parse.initialize(with: parseConfiguration)
PFUser.enableAutomaticUser()
let defaultACL = PFACL();
defaultACL.getPublicReadAccess = true
PFACL.setDefault(defaultACL, withAccessForCurrentUser: true)
if application.applicationState != UIApplicationState.background {
}
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let installation = PFInstallation.current()
installation.setDeviceTokenFrom(deviceToken)
installation.saveInBackground()
PFPush.subscribeToChannel(inBackground: "") { (succeeded, error) in // (succeeded: Bool, error: NSError?) is now (succeeded, error)
if succeeded {
print("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.\n");
} else {
print("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %#.\n", error)
}
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.\n")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %#\n", error)
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handle(userInfo)
if application.applicationState == UIApplicationState.inactive {
PFAnalytics.trackAppOpened(withRemoteNotificationPayload: userInfo)
}
}
}
Error:
2017-10-25 13:08:47.984583+0200 ParseStarterProject-Swift[28036:1825625] [Error]: unauthorized (Code: 0, Version: 1.12.0)
Optional(Error Domain=Parse Code=0 "unauthorized" UserInfo={error=unauthorized, NSLocalizedDescription=unauthorized, temporary=0})
If I write "http://35.19.10.151/" instead of "http://35.19.10.151/parse" I get this:
Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})

Related

Why am I not getting any device token after registering with APNS for push notifications?

I have this code that asks the user to allow my app to receive push notes.
The permission part of it works fine but I never get a device token or any error after I allow the app to receive push notifications.
This is my AppDelegate file:
class AppDelegate: UIResponder, UIApplicationDelegate{
var window: UIWindow?
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions
launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
registerForPushNotifications()
let notificationOption = launchOptions?[.remoteNotification]
if
let notification = notificationOption as? [String: AnyObject],
let aps = notification["aps"] as? [String: AnyObject] {
(window?.rootViewController as? UITabBarController)?.selectedIndex = 1
}
return true
}
func registerForPushNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
print("Permission granted: \(granted)")
guard granted else { return }
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
}
}
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
print("Device Token: \(token)")
}
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
}
I've tried different variations of the same code and still getting no device token. Ive enabled the Push notifications in my project in Xcode and I restarted the my device a few times too.
EDIT:
The didRegisterForRemoteNotificationsWithDeviceToken and didFailToRegisterForRemoteNotificationsWithError are never called for some reason!
Because I am not getting any error or device token at all!

Why is the function in the appdelegate not being called?

I am trying to add the current user to the installation class, but for some reason the function is not being called. What am I doing wrong? How do I fix this? Below is both the finishlaunchingwithoptions and didregisterfornotifications.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Parse.enableLocalDatastore()
// Initialize Parse.
Parse.setApplicationId("***********************",
clientKey: "****************************")
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
if let launchOptions = launchOptions as? [String : AnyObject] {
if let notificationDictionary = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject : AnyObject] {
self.application(application, didReceiveRemoteNotification: notificationDictionary)
}
}
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
// Store the deviceToken in the current Installation and save it to Parse
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation["user"] = PFUser.currentUser()
installation.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if (error == nil){
print("saved installation")
}else{
print(error)
}
})
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError!) {
print("Couldn't register: \(error)")
}
The problem in this situation is that you're running in the iOS Simulator, which does not support remote notifications. So, your didRegisterForRemoteNotificationsWithDeviceToken will never be called, because you're in the simulator. Try on a device and I suspect it will work first time.
For future readers who find this and have a similar problem, the best way to diagnose the problem is to add this to your app delegate:
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("Failed to register for remote notifications: \(error.localizedDescription)");
}
I recommend accomplishing this using a cloud code beforeSave trigger on the Installation class. It's incredibly simple and more robust than trying to handle it client-side. Here's all you need to get the job done:
// Make sure all installations point to the current user
Parse.Cloud.beforeSave(Parse.Installation, function(request, response) {
Parse.Cloud.useMasterKey();
if (request.user) {
request.object.set('user', request.user);
} else {
request.object.unset('user');
}
response.success();
});

Parse ios 9 Swift 2 - App Delegate Errors

Is Parse's documentation code currently not up to date for iOS 9 Swift 2 xcode 7.1? The last 2 functions both have errors saying 'Definition conflicts with previous value'
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.setApplicationId("key",
clientKey: "key")
// Register for Push Notitications
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 pushPayload = false
if let options = launchOptions {
pushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil
}
if (preBackgroundPush || oldPushHandlerOnly || pushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
// Store the deviceToken in the current Installation and save it to Parse
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %#", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
The last 3 functions should be outside of the didFinishLaunchingWithOptions function.

Parse app not working on real device "clang: error: linker command failed with exit code 1" Swift 2.0 Xcode 7 beta 6

I have downloaded the parse core quick start swift Xcode project. It runs perfectly fine in the simulator: I can create users, upload data, etc... But when I try to run it on my physical device I get this error in Xcode: clang: error: linker command failed with exit code 1 (use -v to see invocation) I am sure that I have all the needed library's because the project is strait from parse.com. FWI I'm on Swift 2 Xcode 7 beta 6. I don't think that it's an error in the code but here is my app delegate:
import UIKit
import Bolts
import Parse
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.enableLocalDatastore()
Parse.setApplicationId("XXXXXXXXXXXXXXXXXXXXXXXXXX",
clientKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
PFUser.enableAutomaticUser()
let defaultACL = PFACL();
defaultACL.setPublicReadAccess(true)
PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser:true)
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
PFPush.subscribeToChannelInBackground("") { (succeeded: Bool, error: NSError?) in
if succeeded {
print("good");
} else {
print("bad", error)
}
}
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %#", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
}
And my ViewController.swift:
import UIKit
import Parse
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let testObject = PFObject(className: "TestObject")
testObject["foo"] = "bar"
testObject.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
print("Object has been saved.")
}
}
}
See if deleting your derived data folder fixes it.
Also, you may want to change your Parse keys, since you just posted them on StackOverflow.

Azure + Swift Push Notifications

I am trying to make a VERY simple PUSH from a remote server to an app.
I have set up a notification hub on Azure as per [1], but I cannot get a debug message down to the device. I DO NOT WANT TO READ / WRITE FROM A DB TABLE USING MOBILE SERVICES
I am doing this in Swift, and I have found nothing on the internet that actually receives a push from a server is iOS swift as a complete tutorial.
I do not know, for example, how to write the following code in swift:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// TODO: update #"MobileServiceUrl" and #"AppKey" placeholders
MSClient *client = [MSClient clientWithApplicationURLString:#"MobileServiceUrl" applicationKey:#"AppKey"];
[client.push registerNativeWithDeviceToken:deviceToken tags:#[#"uniqueTag"] completion:^(NSError *error) {
if (error != nil) {
NSLog(#"Error registering for notifications: %#", error);
}
}];
}
So far this is my code in my AppDelegate (some of the code I got from [2]):
var client: MSClient?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if(UIApplication.instancesRespondToSelector(Selector("registerUserNotificationSettings:")))
{
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))
}
/*else
{
//do ios7 stuff here. If you are using just local notifications then you dont need to do anything. for remote notifications:
application.registerForRemoteNotificationTypes(UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge)
}*/
self.client = MSClient(applicationURLString: "[url]", applicationKey: "[key]")
UIApplication.sharedApplication().registerForRemoteNotifications()
let settings = UIUserNotificationSettings(forTypes: .Alert, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
println("Got device token \(deviceToken)");
//IS THIS EVEN CORRECT???? [3] and [4]
/*let json = ("{\"platform\":\"ios\", \"deviceToken\":\"\(deviceToken)\"}" as NSString).dataUsingEncoding(NSUTF8StringEncoding)
self.client?.invokeAPI("register_notifications", data: json, HTTPMethod: "POST", parameters: nil, headers: nil, completion:nil)*/
let registrationTags: [String] = ["tag"];
//EDIT 1 - I HAVE MADE A LITTLE PROGRESS
self.client?.push.registerNativeWithDeviceToken(deviceToken, tags: registrationTags, completion: { (error) -> Void in
println("Error registering")
})
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println("Could not register \(error)");
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
println("Remote notification received!")
println("Awesome!")
}
I am getting a device token back, which means I should be registered, but I do not know how to properly implement [code]
self.client?.push.registerNativeWithDeviceToken(deviceToken: deviceToken, tags: registrationTags, completion: [code])
EDIT 1 I have made some progress here:
self.client?.push.registerNativeWithDeviceToken(deviceToken, tags: registrationTags, completion: { (error) -> Void in
println("Error registering")
})
Now I get an error with registering:
Error Domain=com.Microsoft.WindowsAzureMobileServices.ErrorDomain Code=-1302 "Error: Internal Server Error" UserInfo=0x14d97b10 {NSLocalizedDescription=Error: Internal Server Error, com.Microsoft.WindowsAzureMobileServices.ErrorResponseKey= { URL: https://[servicename].azure-mobile.net/push/registrations%3FdeviceId=[longnumber]&platform=apns } { status code: 500, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 51;
"Content-Type" = "application/json";
Date = "Thu, 05 Mar 2015 08:52:10 GMT";
Server = "Microsoft-IIS/8.0";
"Set-Cookie" = "ARRAffinity=[somehash];Path=/;Domain=[servicename].azure-mobile.net";
"X-Powered-By" = "ASP.NET";
"x-zumo-version" = "Zumo.master.0.1.6.4217.Runtime";
} }, com.Microsoft.WindowsAzureMobileServices.ErrorRequestKey= { URL: https://[servicename].azure-mobile.net/push/registrations%3FdeviceId=[longnumber]&platform=apns }}
EDIT 2
I have now made the following changes after reading [5]:
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let token = NSString(data: deviceToken, encoding: NSUTF8StringEncoding)
println("Got device token");
let hub = SBNotificationHub(connectionString: CONNECTIONSTRING, notificationHubPath: HUBPATH)
hub.registerNativeWithDeviceToken(deviceToken, tags: nil, completion: {(error) -> Void in
println("Error registering: \(error)")
})
}
And the output I now see is:
Got device token
Error registering: nil
I feel like I am making progress but when I send the debug push from Azure I see nothing in my logs (currently when I receive a push I just print a message)
References:
[1] http://azure.microsoft.com/en-us/documentation/articles/notification-hubs-ios-get-started/
[2] Registering for iOS 7 notifications in swift
[3] https://github.com/Azure/azure-content/blob/master/articles/notification-hubs-ios-mobile-services-register-user-push-notifications.md
[4] http://azure.microsoft.com/en-us/documentation/articles/notification-hubs-ios-mobile-services-register-user-push-notifications/
[5] http://azure.microsoft.com/en-us/documentation/articles/notification-hubs-ios-get-started/
This worked fine for me:
let client: MSClient = MSClient(applicationURLString: "https://yoururl.azure-mobile.net/", applicationKey: "yourApplicationKey")
client.push.registerNativeWithDeviceToken(deviceToken, tags: nil, completion: {(error) -> Void in
if error != nil{
NSLog("Error registering for notifications: %#", error)
}
})
This one worked for me. Hope this may help.
var client: MSClient?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
#if !TARGET_IPHONE_SIMULATOR
let notiType:UIUserNotificationType = .Alert | .Badge | .Sound
let settings = UIUserNotificationSettings(forTypes: notiType, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
#endif
self.client = MSClient(applicationURLString:"https://yourAppName.azure-mobile.net/", applicationKey:"yourApplicationKey")
return true
}
func application(application: UIApplication!, didFailToRegisterForRemoteNotificationsWithError error: NSError!) {
println("Failed to register with error: \(error)");
}
func application(application: UIApplication!, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData!) {
let hub = SBNotificationHub(connectionString:"yourConnectionString", notificationHubPath:"yourAppName")
hub.registerNativeWithDeviceToken(deviceToken, tags:nil, completion: { (error) in
if (error != nil) {
println("Error registering for notification: \(error)")
}
})
}
func application(application: UIApplication!, didReceiveRemoteNotification userInfo:[NSObject : AnyObject]?, fetchCompletionHandler:()) {
println("Recived: \(userInfo)")
NSNotificationCenter.defaultCenter().postNotificationName("ReceivedNotification", object:userInfo)
}

Resources