为什么NSUserDefaults不能与Firebase一起使用

时间:2016-09-18 14:40:23

标签: swift firebase firebase-realtime-database nsuserdefaults

我正在使用Firebase登录并使用NSUserdefaults保存uid,以便下次自动登录。但不知道为什么它不起作用。以下是我的代码:

 // let's say path is the route down to "users" in Firebase  
  @IBAction func loginPressed(sender: AnyObject) {        
    if let email = emailField.text where email != "", let password = passwordField.text where password != "" {            
        FIRAuth.auth()?.signInWithEmail(email, password: password, completion: { (user, err) in                
            if err != nil {                    
                print(err)                    
            } else {                    
            NSUserDefaults.standardUserDefaults().setValue(user!.uid, forKey: "uid")                    
           path.child("\(user!.uid)/category").observeSingleEventOfType(.Value, withBlock: { (snapshot) in

             if let userCategory = snapshot.value as? String {                        
               if userCategory == "seller" {                            
                  self.performSegueWithIdentifier(segueSellerVC, sender: self)                            
                } else  {                            
                    self.performSegueWithIdentifier(segueCustomerVC, sender: self)                            
                    }
                }                    
               })                                        
           }                
       })
    }     
}

2 个答案:

答案 0 :(得分:3)

Swift 3

保存

#include <stdio.h>
#include <math.h>
#define PI 3.14159265358979323846
#define GRAVITY 9.8
#define ANGLE_RAD45 0.7853981634


typedef struct Artillery
{
    char name[30];
    float muzzleVelocity;
    float minAngleOfElevation;
    float maxAngleOfElevation;
}Artillery;


typedef struct Projectile
{
    char name[30];
    double blastRadius;
}Projectile;


// Function header: artillery struct
void PrintArtillery(Artillery artillery);

// Function header: projectile struct
void PrintProjectile(Projectile projectile);

// Function header: max range
double CalculateRange(double velocity, double angle);

// Function header: deg to rad angle conversion
double AngleDegToRad(double angle);

// Function header: air time
double CalculateAirTime(double velocity, double angle);

// Function header: simulate projectile location
void SimulateProjectile(double* height, double* distance, double time, double velocity, double angle);


int main(void)
{
    // Variables
    int userValue;
    int userValueTwo;
    double userTargetDist;

    double angleRad;
    double userAngle;
    double maxRange;
    double airTime; 

    double cannonMaxR = 200;
    double howitzMaxR = 900;
    double mortarMaxR = 805;

    double simHeight; //passive variable
    double simDistance;
    double simTime;


    // Array of 3 weapons
    Artillery weapon[3];

    // Generate weapons
    weapon[0] = (Artillery) { "Cannon", 200, 0, 45 };
    weapon[1] = (Artillery) { "Howitzer", 900, 20, 65 };
    weapon[2] = (Artillery) { "Mortar", 805, 50, 85 };

    // Print title of artillery menu    
    printf("\n|Artillery Weapon\t|Muzzle Velocity\t|Min Elevation\t\t|Max Elevation\n");
    printf("--------------------------------------------------------------------------------\n");

    int i;
    for(i = 0; i < 3; i++)
    {
        PrintArtillery(weapon[i]);
    }

    printf("Please select an artillery weapon (1, 2 or 3)\n");
    scanf("%i", &userValue);

    while(userValue < 1 || userValue > 3)
    {
        printf("Input is invalid\nPlease use the appropriate values to select your gun (1, 2, 3)\n");
        scanf("%i", &userValue);
        fflush(stdin);
    }


    // Array of 3 shells
    Projectile ammoType[3];

    // Generate ammo types
    ammoType[0] = (Projectile) { "High Explosive Anti-Tank", 5 };
    ammoType[1] = (Projectile) { "M549 HERA             ", 15 };
    ammoType[2] = (Projectile) { "W19 Katie AFAP        ", 4200 };

    // Print title of projectile menu
    printf("\n|Projectile Shell\t\t|Blast Radius\n");
    printf("-------------------------------------------\n");

    // Loop data
    int ii;
    for(ii = 0; ii < 3; ii++)
    {
        PrintProjectile(ammoType[ii]);
    }

    // Ask user to selection shell
    printf("Please select a shell (1, 2 or 3)\n");
    scanf("%i", &userValueTwo);

    // Apply warning when input is invalid
    while(userValueTwo < 1 || userValueTwo > 3)
    {
        printf("Input is invalid\nPlease use the appropriate values to select your shell (1, 2, 3)\n");
        scanf("%i", &userValueTwo);
        fflush(stdin);
    }


// HOW DO I USE USER'S TARGETDIST TO SHOW HIT OR MISS AT THE END OF SIMULATION???


// Ask user for distance to target in m
printf("Please enter the distance to the target in metres\n");
scanf("%lf", &userTargetDist);


// Make decisions after verified user's inputs
switch(userValue)
{   
    case 1:

        // Start calc after verified ans
        // Run max range func (tells max range of gun)
        maxRange = CalculateRange(mortarMaxR, angleRad);

        // Print instructions
        printf("Please enter the angle of elevation in degrees\n"); 

        scanf("%lf", &userAngle);

        // Validate user input          
        while(userAngle < 0 || userAngle > 45)
        {
            printf("Input is invalid\nThe angle of elevation must be between 50.00 to 85.00 degrees\n");
            scanf("%lf", &userAngle);
            fflush(stdin);
            continue;
        }   

        // Start calc after verified answers
        if(userAngle > 0 || userAngle < 45)
        {   
            // Run deg to rad angle conversion func
            angleRad = AngleDegToRad(userAngle);

            // Run air time func
            airTime = CalculateAirTime(mortarMaxR, angleRad);       

            // Sim loop starts here (track proj location)
            for(simTime = 1; simTime <= airTime; simTime++)
            {
                SimulateProjectile(&simHeight, &simDistance, simTime, mortarMaxR, angleRad);
            }

            // Print total distance travelled & total air time
            printf("The projectile has hit ground level!\nTotal distance travelled: %f\nTotal air time: %f\n", simDistance, airTime);}  

        break;



    case 2:

        // Run max range func (tells max range of gun)
        maxRange = CalculateRange(howitzMaxR, angleRad);

        // Print instructions
        printf("Please enter the angle of elevation in degrees\n"); 

        scanf("%lf", &userAngle);

        // Validate user input          
        while(userAngle < 20 || userAngle > 65)
        {
            printf("Input is invalid\nThe angle of elevation must be between 20.00 to 65.00 degrees\n");
            scanf("%lf", &userAngle);
            fflush(stdin);
            continue;
        }   

        // Start calc after verified answers
        if(userAngle > 20 || userAngle < 65)
        {   
            // Run deg to rad angle conversion func
            angleRad = AngleDegToRad(userAngle);

            // Run air time func
            airTime = CalculateAirTime(howitzMaxR, angleRad);       

            // Sim loop starts here (track proj location)
            for(simTime = 1; simTime <= airTime; simTime++)
            {
                SimulateProjectile(&simHeight, &simDistance, simTime, howitzMaxR, angleRad);
            }

            // Print total distance travelled & total air time
            printf("The projectile has hit ground level!\nTotal distance travelled: %f\nTotal air time: %f\n", simDistance, airTime);
        }   

        break;      



    case 3:

        // Run max range func (tells max range of gun)
        maxRange = CalculateRange(mortarMaxR, angleRad);

        // Print instructions
        printf("Please enter the angle of elevation in degrees\n"); 

        scanf("%lf", &userAngle);

        // Validate user input          
        while(userAngle < 50 || userAngle > 85)
        {
            printf("Input is invalid\nThe angle of elevation must be between 50.00 to 85.00 degrees\n");
            scanf("%lf", &userAngle);
            fflush(stdin);
            continue;
        }   

        // Start calc after verified answers
        if(userAngle > 50 || userAngle < 85)
        {   
            // Run deg to rad angle conversion func
            angleRad = AngleDegToRad(userAngle);

            // Run air time func
            airTime = CalculateAirTime(mortarMaxR, angleRad);       

            // Sim loop starts here (track proj location)
            for(simTime = 1; simTime <= airTime; simTime++)
            {
                SimulateProjectile(&simHeight, &simDistance, simTime, mortarMaxR, angleRad);
            }

            // Print total distance travelled & total air time
            printf("The projectile has hit ground level!\nTotal distance travelled: %f\nTotal air time: %f\n", simDistance, airTime);
        }   

        break;  
}

return 0;
}   


//-----FUNCTION CALCULATIONS-----//

// Function calculation: artillery struct
void PrintArtillery(Artillery artillery)
{
    // Print variables of artillery menu
    printf("|%s   \t\t|%f m/s\t\t\|%f deg\t\t\t|%f deg\t\n\n",  artillery.name, 
                                                                artillery.muzzleVelocity, 
                                                                artillery.minAngleOfElevation, 
                                                                artillery.maxAngleOfElevation);
}

// Function calculation: projectile struct
void PrintProjectile(Projectile projectile)
{
    // Print variables of projectile menu
    printf("|%s\t|%lf metres\n\n",   projectile.name, projectile.blastRadius);
}

// Function calculation: max range
double CalculateRange(double velocity, double angle)
{
    double maxRange;
    maxRange = (velocity*velocity/GRAVITY)*sin(2*ANGLE_RAD45);
    printf("Maximum range: %.2lf\n", maxRange);
    return maxRange;
}

// Function calculation: deg to rad angle conversion
double AngleDegToRad(double angle)
{
    double angleRad;
    angleRad = angle*(PI/180);
    return angleRad;
}

// Function calculation: air time
double CalculateAirTime(double velocity, double angle)
{
    double airTime;
    airTime = (2*velocity*sin(angle))/GRAVITY;
    return airTime;
}

// Function calculation: projectile location sim
void SimulateProjectile(double* height, double* distance, double time, double velocity, double angle)
{
    *height = (velocity*time)*sin(angle)-(0.5*GRAVITY*(time*time));
    *distance = (velocity*time)*cos(angle);
    printf("At %f second(s), height is: %f and distance is: %f\n", time, *height, *distance);
}

检索

UserDefaults.standard.set(FIRAuth.auth()!.currentUser!.uid, forKey: "uid")

UserDefaults.standard.synchronize()

Swift 2

保存

let storagePath = UserDefaults.standard.object(forKey: "uid") as? String 

检索

NSUserDefaults.standardUserDefaults().setObject(FIRAuth.auth()!.currentUser!.uid, forKey: "uid")

NSUserDefaults.standardUserDefaults().synchronize()

答案 1 :(得分:0)

Swift 3

UserDefaults.standard.setValue(user!.uid, forKey: "uid")