Creating login/signup views in Xcode - ios

I am making an app for iOS in Xcode.
My question is:
How do I make the app show the signup/login view when it is needed, but not show it when the user is already logged in?
Is it communicating with the database every time the app launches?
I am planning on using MySQL for creating a database with simple users (username, score, friends).
Is there a tutorial that will show me the steps for doing this?
I have no experience with databases.
Help is appreciated.

I'm gonna give you a comprehensive answer.
Don't use NSUserDefaults and don't store password it's a bad solution
NSUserDefaults data is not encrypted, it may cause security issue.
Let's create a structured user class instead
When the user logged in, you will need to make sure you have access to user data throughout the app so you can get the data on any screen when you need it.
To achieve this, we need to make a great structure to organize this properly. Remember that current user and another users are both "user" so we will use the same class.
Create a class and name it "EDUser" (you can choose other name if you want).
This class will contain a user information (either current user or other user).
More than that, this class will have capability to log the user in.
Here's a picture of what the class might look like:
class EDUser {
var firstName: String
var lastName: String?
var birthDate: NSDate?
init(firstName: String, lastName: String?, birthDate: NSDate?) {
self.firstName = firstName
self.lastName = lastName
self.birthDate = birthDate
}
}
// MARK: - Accessor
extension EDUser {
class var currentUser: EDUser? {
get {
return loadCurrentUserFromDisk()
}
set {
saveCurrentUserToDiskWithUser(newValue)
}
}
}
// MARK: - Log in and out
extension EDUser {
class func loginWithUsername(username: String,
andPassword password: String,
callback: (EDUser?, NSError) -> Void) {
// Access the web API
var parameters = [
"username": username,
"password": password
]
YourNetworkingLibrary.request(.POST,
"https://api.yourwebsite.com/login",
parameters: parameters).responseJSON {
response in
if response.statusCode == .Success {
let user = EDUser(firstName: response["firstName"],
lastName: response["lastName"],
birthDate: NSDate.dateFromString(response["birthDate"]))
currentUser = user
callback(currentUser, nil)
} else {
callback(nil, yourError)
}
}
}
class func logout() {
deleteCurrentUserFromDisk()
}
}
// MARK: - Data
extension EDUser {
class private func saveCurrentUserToDiskWithUser(user: EDUser) {
// In this process, you encode the user to file and store it
}
class private func loadCurrentUserFromDisk() -> EDUser? {
// In this process, you get the file and decode that to EDUser object
// This function will return nil if the file is not exist
}
class private func deleteCurrentUserFromDisk() {
// This will delete the current user file from disk
}
}
// MARK: - Helper
extension NSDate {
class func dateFromString(string: String) -> NSDate {
// convert string into NSDate
}
}
Use Case
Now with everything in place, we can use it like this
Non-blocking logging in process
EDUser.loginWithUsername(username: "edward#domain.com",
password: "1234") {
user, error in
if error == nil {
// Login succeeded
} else {
// Login failed
}
}
Logging out
EDUser.logout()
Check whether the user is logged in
if EDUser.currentUser != nil {
// The user is logged in
} else {
// No user logged in
// Show the login screen here
}
Get current user data on any screen
if let currentUser = EDUser.currentUser {
// do something with current user data
}
Store other user as object
let user = EDUser(firstName: "Edward",
lastName: "Anthony",
birthDate: NSDate())

You need to look at a bunch of tutorials, I recommend these guys:
https://www.raywenderlich.com
They have free tutorials in ObjC and Swift as well as video courses!

A REST API normally respond with a 401 (Unauthorized code) if there isn't a valid/logged user, so every time I get a 401 I show a login within a modal view.
So when you load the app, call a GET currentUser endpoint, if it returns a 401 the app will show the login, if not, the app will show the default rootViewController.
I like this way because if for any reason, your session is no longer valid, the app will show the login view.

Related

Access modification Apple Combine

I'm trying to think in terms of API Design because ultimately I want to ship code to myself or others.
Let's make some assumptions in order to get a succinct scenario. We will assume I have some Code that authenticates with my server and returns a user object. Defined simply like this:
public struct User: Codable {
public let id: UUID
public let email: String
public let name: String
}
I'm writing this code as an SDK I would ship to myself or a third party where all the guts of AUTH are handled. Using Apples new Combine framework I might expose a publisher for the consumer of my SDK like this.
public enum CurrentUserError: Error {
case loggedOut
case sessionExpired
}
public struct MyAuthFrameworkPublishers {
static let currentUser: CurrentValueSubject<User?, CurrentUserError> = CurrentValueSubject<User?, CurrentUserError>(nil)
}
Now, my private auth could accomplish it's task and retrieve a user then publish that to anything outside the SDK that it listening like so:
class AuthController {
func authenticate() {
///Get authenticated user.
let user = User.init(id: UUID(), email: "some#some.com", name: "some")
MyAuthFrameworkPublishers.currentUser.send(user)
}
}
let authController = AuthController.init()
authController.authenticate()
Is there a way to keep or stop the user of this SDK from sending it's own User object to the publisher? Like a private or access controller .send() function in combine?
Do you really want to use CurrentUserError as your Failure type? Sending a failure ends any subscriptions to the subject and fails new ones immediately. If the session expires, don't you want to let the user log in again? That would require publishing another User? output, which you cannot do if you have published a failure.
Instead, use Result<User?, CurrentUserError> as your Output type, and Never as your Failure type.
Now, on to your question. In general, the way to prevent the user from calling send is to vend an AnyPublisher instead of a Subject:
public class AuthController {
public let currentUser: AnyPublisher<Result<User?, AuthenticationError>, Never>
public func authenticate() {
let user: User = ...
subject.send(user)
}
public init() {
currentUser = subject.eraseToAnyPublisher()
}
private let subject = CurrentValueSubject<Result<User?, AuthenticationError>, Never>(nil)
}

Firebase modifying uid in every view

I'm new to swift and I'm trying to make a sign-up form using multiple views. The problem is that after calling Auth.auth().currentUser?.uid
I get a different String in each view, being unable to continue doing work on one specific UID. What am I doing wrong?
I'm creating the user using the firebase function createUser as so:
Auth.auth().createUser(withEmail: emailField.text!, password:
passField.text!, completion: { (user, error) in
if let error = error {
print(error)
}
if let user = user {
let userInfo: [String : Any] = ["uid": UserModel().getUID(),
"username": self.usernameField.text!, "avatar_icon" : ""]
self.ref.child("users").child(user.uid).setValue(userInfo)
}
})
I've tried creating a model class that holds that specific string, but getting the same bad results.
import Foundation
import Firebase
class UserModel {
var userID : String
init() {
self.userID = (Auth.auth().currentUser?.uid)!
}
func getUID() -> String {
return self.userID
}
}
My first sign-up view controller is Register1ViewController, where I call UserModel.init(), getting the uid with UserModel().getUID() in the future view controllers.
At firebase every authenticated user have only one "unique" uID as you know. So when you logged in as a user, you should allways get the same uID when you query it. It is hard to say this from here because you provided little part of this code. You should provide more to get an answer.
EDIT:
It looks like you are calling createuser everytime your activity starts. That means you are creating another user every time you run the code. And the
Auth.auth().currentUser?.uid
returns you different uID. You should register once and log-in other times. You can check tutorial below. But dont just look snippets, open github code.
https://www.appcoda.com/firebase-login-signup/

How to prevent Parse from saving PFObject children's?

I'm facing a very common issue with Parse and iOS.
I have a class POST with the following structure:
text(String)
Image (PFFile)
LikesUsers (Array of String)
LikesCount (Int)
From (Pointer to User who posted it)
and if the user (already logged in) likes a post. I'm just incrementing the likes and the add Objectid of the user to the array
For example : User-2 likes User-1's Post.
PostObject.incrementKey("Likes")
PostObject.addObject((PFUser.currentUser()?.objectId)!, forKey: "LikesUsers")
PostObject.saveEventually()
The issue is here. I can't save a the PostObject as long as it has a pointer to another user (than the logged in) I'm getting the error :
User cannot be saved unless they have been authenticated via logIn or
signUp
So how to prevent from saving the ParseObject Children ("From")
I don't want to use a CloudCode, I want to keep it simple and to Use SaveEventually for a better user experience.
From the parse.com forums:
When you save an object with a pointer, Parse looks at the entirety of the object and saves the fields that are "dirty" (changed since last save). It also inspects all the objects being pointed to by pointers. If your object has a pointer to PFUser and the instance of the PFUser is "dirty", then Parse will save the object and then attempt to save the instance of the PFUser as well. My hypothesis is that somewhere in your code you are setting a value on a user and then not saving the user. This, I suspect, is the source of your error. Go through your code and look for anywhere you set a PFUser instance and make sure there's a corresponding save. If you can't find it at first glance, be sure to check all blocks and ensure that you are not asynchronously dirtying a user and subsequently trying to save it.
Are you trying to make any changes to the user that the post was made by?
Short answer:
Try to set from field as:
let author = PostObject["from"] as! PFObject
PostObject["from"] = PFObject(withoutDataWithClassName: "_User",
objectId: author.objectId)
This is not tested.
But I suggest you to change the architecture
I was facing the same problem and finally decided to move likes field to User class instead and make it Relation<Post> type. Parse documentation says that Relation type is better for keeping many objects. Since LikesUsers is an array of objects, the performance may drop significantly if a post will get many likes: the app will download all the users liked this post. See this for more info: https://parse.com/docs/ios/guide#objects-relational-data
Here is how my class structure looks like (simplified):
User:
postLikes (Relation)
Post:
author (PFObject)
likesCount (Int)
I also moved like/dislike logic to CloudCode function:
/// The user liked or disliked the post.
Parse.Cloud.define("likeDislikePost", function(request, response) {
var userProfileId = request.params.userProfileId
var postId = request.params.postId
// Shows whether the user liked or disliked the post. Bool value
var like = request.params.like
var query = new Parse.Query("_User");
query.equalTo("objectId", userProfileId);
query.first({
success: function(userProfile) {
if (userProfile) {
var postQuery = new Parse.Query("Post");
postQuery.equalTo("objectId", postId);
postQuery.first({
success: function(post) {
if (post) {
var relation = userProfile.relation("postLikes");
if (like) {
relation.add(post);
post.increment("likesCount");
}
else {
relation.remove(post)
post.increment("likesCount", -1);
}
post.save();
userProfile.save();
console.log("The user with user profile id " + userProfileId + " " + (like ? "liked" : "disliked") + " the post with id " + postId);
response.success();
}
else {
response.error("Unable to find a post with such ID");
}
},
error: function() {
response.error("Unable to like the post");
}
});
}
else {
response.error("Unable to find a user profile with such ID");
}
},
error: function() {
response.error("Unable to like the post");
}
});
});
Works just fine.
I created some project from scratch for you. I think you miss some thing when you are creating your PFClass. I don't know. Whatever look my codes,
This is the ViewController and it contains like Button Action;
import UIKit
class ViewController: UIViewController {
private let test = Test() // PFObject SubClass
private let post = Post() // PFObject SubClass
#IBAction func likeButton() {
self.test.fromUser = PFUser.currentUser() // Current User
self.test.likedUsers.append(Post().user // In there your post should be a Subclass of PFObject too like your this Test class and it should be contains Owner property. So you can grab the Post owner PFUser or User Object ID.)
self.test.saveEventually() {
(let success, error) in
if error == nil {
// Success
} else {
print(error?.localizedDescription)
}
}
}
}
In your AppDelegate init your ParseSDK and Register your new Parse subclasses.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Parse.setApplicationId("YOUR_API_KEY", clientKey: "YOUR_CLIENT_KEY")
Test.registerSubclass()
Post.registerSubclass()
return true
}
Test Subclass;
import Foundation
import Parse
class Test: PFObject, PFSubclassing {
// Your Properties
#NSManaged var likedUsers: [PFUser]
#NSManaged var fromUser: PFUser
static func parseClassName() -> String {
return "Test" // Your Class Name
}
}
Post Subclass;
class Post: PFObject, PFSubclassing {
// Your Properties
#NSManaged var owner: PFUser
#NSManaged var likeCount: NSNumber
static func parseClassName() -> String {
return "Post" // Your Class Name
}
}
In my case it works fine. If you get an error please inform me.
Have a nice coding.

Subclassing PFUser does not effect the data stored

I am using Swift.
This question talks about the Parse service.
I've read ways using both the #NSManaged and dynamic key-words, so I decided for my example to implement them both. The issue here is that in the User object of my data manager, I'm noticing that additional information is not being stored in the database. For my application I would like to store some additional information in the User table, such as their first and last name. Here's an example:
import Parse
public class User : PFUser {
#NSManaged public var firstName: String!
dynamic public var lastName: String!
override public class func initialize() {
struct Static {
static var onceToken : dispatch_once_t = 0
}
dispatch_once(&Static.onceToken) {
self.registerSubclass()
}
}
init(email: String, password: String) {
super.init();
self.username = email;
self.email = email;
self.password = password;
self.firstName = "MyFirstName";
self.lastName = "MyLastName";
}
}
Here's the code I'm using to initialize and send off the data:
#IBAction func register() {
let newUser = User(email: "myemail#provider.com", password: "my password");
newUser.signUpInBackgroundWithBlock { (success, error) -> Void in
if error == nil {
print("Success")
} else {
print(error);
}
}
}
Edit: Upon playing around in the dashboard it seems like fields that are added to the User table / document / whatever you want to call it in a schema less database are automatically removed. This would indicate that I would need to create another class (IE: UserInfo) to store all of the users information, such as first and last name. Is this correct? If so that seems a little odd, as it would increase the amount of requests to login to the application. (One for validation, one for retrieving information). Is this the correct way of handling this?
Adding properties to a subclass won't them automatically added to the PFUser instance. You will have to use the PFObject methods to set the properties and then save the PFUser object.
The Parse Documentation gives an example of setting an extra phone property on the PFUser instance before calling signup. This is how you can add the firstName and lastName properties to PFUser.

Xcode iOS: check if user is logged in and show different views if not

I'm coding an app where a logged in user has got a couple of extra functionalities than a non logged in user. Basically, I have more or less 5 tabs. When I launch the app, the user immediately gets the login page. He can decide to skip it. If he skips it, there'll only be 3 tabs for him. If he logs in successfully, there'll be 5.
I already have my login page made. I just don't know how I can store a session if the user is logged in correctly, and only display a certain number of tabs if the user isn't. I come from PHP, I've just started learning Objective-C, so I'm looking for the same thing as $_SESSION in PHP, more or less.
So: if user logs in, store session, and show all the tabs. If he doesn't, only show a limited number of tabs.
How should I approach this?
In terms of storing the session, I assume username and password is enough.
You could store the username as you wish in NSUserDefaults or CoreData if you are using it. Storing a password is best using the keychain. SSKeychain makes it easy to do this.
[SSKeychain setPassword:password forService:myAppName account:userName]
You could store the fact they are logged in in-memory, but on app relaunch check by:
NSString *password = [SSKeychain passwordForService:myAppName account:userName];
if (password != nil)
{
// Logged in
}
If the user logs out, easy as deleting the password from the keychain by
[SSKeychain deletePasswordForService:myAppName account:userName]
Session handling is done automatically when you use NSURLConnection, so you can store the users data in a Sesssion on the server.
What you might be looking for is called a Singleton design pattern (some people reject it, but it can be very handy). What you do is create one object that is available everywhere in your code. In this object you for example store a BOOL that indicates whether the user has logged in or not. For example:
(I didn't run this, just to get the idea)
Mananger myManager* = [Manager sharedManager];
if(myManager.loggedIn){
//Show 5 tabs
}else{
//Show 3 Tabs
}
This code can be used in every class so you can always access your user's data. Manager would be a seperate class in this case that provides singleton functionality. Check out how to make one here: http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/
I'm gonna give you a comprehensive answer.
Don't use NSUserDefaults as session it's a bad solution
NSUserDefaults data is not encrypted, it may cause security issue.
Let's create a structured user class instead
When the user logged in, you will need to make sure you have access to user data throughout the app so you can get the data on any screen when you need it.
To achieve this, we need to make a great structure to organize this properly. Remember that current user and another users are both "user" so we will use the same class.
Create a class and name it "EDUser" (you can choose other name if you want).
This class will contain a user information (either current user or other user).
More than that, this class will have capability to log the user in.
Here's a picture of what the class might look like:
class EDUser {
var firstName: String
var lastName: String?
var birthDate: NSDate?
init(firstName: String, lastName: String?, birthDate: NSDate?) {
self.firstName = firstName
self.lastName = lastName
self.birthDate = birthDate
}
}
// MARK: - Accessor
extension EDUser {
class var currentUser: EDUser? {
get {
return loadCurrentUserFromDisk()
}
set {
saveCurrentUserToDiskWithUser(newValue)
}
}
}
// MARK: - Log in and out
extension EDUser {
class func loginWithUsername(username: String,
andPassword password: String,
callback: (EDUser?, NSError) -> Void) {
// Access the web API
var parameters = [
"username": username,
"password": password
]
YourNetworkingLibrary.request(.POST,
"https://api.yourwebsite.com/login",
parameters: parameters).responseJSON {
response in
if response.statusCode == .Success {
let user = EDUser(firstName: response["firstName"],
lastName: response["lastName"],
birthDate: NSDate.dateFromString(response["birthDate"]))
currentUser = user
callback(currentUser, nil)
} else {
callback(nil, yourError)
}
}
}
class func logout() {
deleteCurrentUserFromDisk()
}
}
// MARK: - Data
extension EDUser {
class private func saveCurrentUserToDiskWithUser(user: EDUser) {
// In this process, you encode the user to file and store it
}
class private func loadCurrentUserFromDisk() -> EDUser? {
// In this process, you get the file and decode that to EDUser object
// This function will return nil if the file is not exist
}
class private func deleteCurrentUserFromDisk() {
// This will delete the current user file from disk
}
}
// MARK: - Helper
extension NSDate {
class func dateFromString(string: String) -> NSDate {
// convert string into NSDate
}
}
Use Case
Now with everything in place, we can use it like this
Non-blocking logging in process
EDUser.loginWithUsername(username: "edward#domain.com",
password: "1234") {
user, error in
if error == nil {
// Login succeeded
} else {
// Login failed
}
}
Logging out
EDUser.logout()
Check whether the user is logged in
if EDUser.currentUser != nil {
// The user is logged in
} else {
// No user logged in
// Show the login screen here
}
Get current user data on any screen
if let currentUser = EDUser.currentUser {
// do something with current user data
}
Store other user as object
let user = EDUser(firstName: "Edward",
lastName: "Anthony",
birthDate: NSDate())

Resources