Cara Fetch dan Update Data User di Mobile Aplikasi iOS Menggunakan Mesosfer

Tutorial Fetch dan Update Data User menggunakan Mesosfer.

Jika sebelumnya Anda telah mengikuti tutorial ini di website Codepolitan, ini adalah tutorial lanjutan dari tutorial sebelumnya. Di tutorial sebelumnya kita belajar tentang membuat login dan session check, kali ini kita lanjutkan dengan fetch dan update data user di mobile aplikasi iOS. Untuk yang belum mengikuti, bisa cek tutorialnya di web Codepolitan.

Saya akan menyediakan tutorial ini dalam Objective-C dan Swift persis seperti tutorial asli agar memudahkan Anda menyesuaikan dengan bahasa pemrograman kalian. Sebelumnya tutorial ini telah di pos di blog Mesosfer dalam bahasa Inggris, agar lebih mudah untuk dipahami.

Untuk detail mengenai Apa itu Mesosfer, silakan kunjungi Mesosfer Documentation.

Hal yang Perlu Disiapkan

Start the Code!

3.1 Buat design tampilan terlebih dahulu

Tambahkan static cell untuk profile menu di main view. Lalu tambahkan profile view pada main.storyboard. Hubungkan new menu dan profile view dengan Triggered Segues -> Selection -> Show seperti dibawah:

fetch data

Sama seperti register view, Profile view berisi:

  • Seperti Email Address (UITextField), used for entering login email credential.
  • First Name (UITextField), Digunakan untuk memasukkan first name dari user.
  • Last Name (UITextField), Digunakan untuk memasukkan last name user.
  • Birth of Date (UITextField), Digunakan untuk memasukkan tanggal lahir dengan format "yyy-mm-dd".
  • Height (UITextField), digunakan untuk memasukkan tinggi badan (double number) dari user.
  • Weight (UITextField), Digunakan untuk memasukkan berat badan (integer number) dari user.
  • IsMarried (UISwitch), digunakan untuk memilih status dari user.
  • Update Profile (UITableViewCell), Digunakan untuk update data user ke Mesosfer Cloud.

Sebagai tambahan, Anda bisa menambahkan tampilan untuk merubah password:

  • Old Password (UITextField), merupakan password user saat ini yang digunakan untuk login.
  • New Password (UITextField), merupakan password baru yang digunakan untuk merubah password lama yang digunakan login oleh user.
  • Confirm New Password (UITextField), Digunakan untuk konfirmasi password baru yang baru saja dimasukkan.
  • Change Password (UITableViewCell), Digunakan untuk merubah user password ke Mesosfer Cloud.

3.2 Referencing the Outlets

Tambahkan ProfileViewController class ke Xcode project, kemudian tambahkan referencing outlet untuk tiap object library:

Objective-C

@property (weak, nonatomic) IBOutlet UITextField *textEmail;
@property (weak, nonatomic) IBOutlet UITextField *textFirstName;
@property (weak, nonatomic) IBOutlet UITextField *textLastName;
@property (weak, nonatomic) IBOutlet UITextField *textDateOfBirth;
@property (weak, nonatomic) IBOutlet UITextField *textHeight;
@property (weak, nonatomic) IBOutlet UITextField *textWeight;
@property (weak, nonatomic) IBOutlet UISwitch *switchIsMarried;

@property (weak, nonatomic) IBOutlet UITextField *textOldPassword;
@property (weak, nonatomic) IBOutlet UITextField *textNewPassword;
@property (weak, nonatomic) IBOutlet UITextField *textConfirmPassword;

Swift

@IBOutlet weak var textEmail: UITextField!
@IBOutlet weak var textFirstName: UITextField!
@IBOutlet weak var textLastName: UITextField!
@IBOutlet weak var textDateOfBirth: UITextField!
@IBOutlet weak var textHeight: UITextField!
@IBOutlet weak var textWeight: UITextField!
@IBOutlet weak var switchIsMarried: UISwitch!
@IBOutlet weak var textOldPassword: UITextField!
@IBOutlet weak var textNewPassword: UITextField!
@IBOutlet weak var textConfirmPassword: UITextField!

3.3 Lengkapi Code

3.3.1 ProfileViewController code lengkap:

Objective-C

#import 

@interface ProfileViewController : UITableViewController

@property (weak, nonatomic) IBOutlet UITextField *textEmail;
@property (weak, nonatomic) IBOutlet UITextField *textFirstName;
@property (weak, nonatomic) IBOutlet UITextField *textLastName;
@property (weak, nonatomic) IBOutlet UITextField *textDateOfBirth;
@property (weak, nonatomic) IBOutlet UITextField *textHeight;
@property (weak, nonatomic) IBOutlet UITextField *textWeight;
@property (weak, nonatomic) IBOutlet UISwitch *switchIsMarried;

@property (weak, nonatomic) IBOutlet UITextField *textOldPassword;
@property (weak, nonatomic) IBOutlet UITextField *textNewPassword;
@property (weak, nonatomic) IBOutlet UITextField *textConfirmPassword;

@end
  • .m file
#import "ProfileViewController.h"
#import "UIViewController+Helper.h"
#import 

@implementation ProfileViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self reloadUserData];
}

- (void)reloadUserData {
    MFUser *user = [MFUser currentUser];
    if (user) {
        self.textEmail.text = user.email;
        self.textFirstName.text = user.firstname;
        self.textLastName.text = user.lastname;
        
        NSDate *date = [user dateForKey:@"dateOfBirth"];
        if (date) {
            self.textDateOfBirth.text = [[MFDateFormatter sharedFormatter] stringFromDate:date isTimestamp:NO];
        }
        self.textHeight.text = [NSString stringWithFormat:@"%@", [user numberForKey:@"height"]];
        self.textWeight.text = [NSString stringWithFormat:@"%@", [user numberForKey:@"weight"]];
        self.switchIsMarried.on = [user booleanForKey:@"isMarried"];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // update profile
    if (indexPath.section == 2 && indexPath.row == 0) {
        NSString *email = self.textEmail.text;
        NSString *firstname = self.textFirstName.text;
        NSString *lastname = self.textLastName.text;
        
        NSString *dateOfBirth = self.textDateOfBirth.text;
        NSString *height = self.textHeight.text;
        NSString *weight = self.textWeight.text;
        BOOL isMarried = self.switchIsMarried.on;
        
        MFUser *user = [MFUser currentUser];
        if (user) {
            // set required field
            user.email = email;
            user.firstname = firstname;
            user.lastname = lastname;
            // set custom field
            NSDate *date = [[MFDateFormatter sharedFormatter] dateFromString:dateOfBirth];
            if (date) {
                user[@"dateOfBirth"] = date;
            }
            user[@"height"] = [NSNumber numberWithDouble:[height doubleValue]];
            user[@"weight"] = [NSNumber numberWithInt:[weight intValue]];
            user[@"isMarried"] = [NSNumber numberWithBool:isMarried];
            // update user data async
            [user saveAsyncWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                if (error) {
                    [self showErrorWithTitle:@"Failed to update profile" error:error handler:nil];
                    return;
                }
                
                [self showAlertWithTitle:@"Profile updated"
                                 message:@"Your profile's has been successfully updated." handler:nil];
            }];
        }
    } // change password
    else if (indexPath.section == 4 && indexPath.row == 0) {
        NSString *oldPassword = self.textOldPassword.text;
        NSString *newPassword = self.textNewPassword.text;
        NSString *confirmPassword = self.textConfirmPassword.text;
        
        if ([oldPassword isEqualToString:newPassword]) {
            [self showAlertWithTitle:nil message:@"Old and new password are equal." handler:nil];
            return;
        }
        
        if (![newPassword isEqualToString:confirmPassword]) {
            [self showAlertWithTitle:nil message:@"New and confirm password are not equal." handler:nil];
            return;
        }
        
        MFUser *user = [MFUser currentUser];
        if (user) {
            [user changePasswordAsyncWithOldPassword:oldPassword
                                         newPassword:newPassword
                                               block:^(BOOL succeeded, NSError * _Nullable error) {
                if (error) {
                    [self showErrorWithTitle:@"Failed to change password" error:error handler:nil];
                    return;
                }
                
                [self showAlertWithTitle:nil message:@"Password changed successfully." handler:nil];
            }];
        }
    }
}

@end

Swift

import Foundation
import UIKit
import Mesosfer

class ProfileViewController: UITableViewController {
    @IBOutlet weak var textEmail: UITextField!
    @IBOutlet weak var textFirstName: UITextField!
    @IBOutlet weak var textLastName: UITextField!
    @IBOutlet weak var textDateOfBirth: UITextField!
    @IBOutlet weak var textHeight: UITextField!
    @IBOutlet weak var textWeight: UITextField!
    @IBOutlet weak var switchIsMarried: UISwitch!
    @IBOutlet weak var textOldPassword: UITextField!
    @IBOutlet weak var textNewPassword: UITextField!
    @IBOutlet weak var textConfirmPassword: UITextField!
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // reload user data and set into form
        self.reloadUserData()
    }
    
    func reloadUserData() {
        if let user = MFUser.currentUser() {
            self.textEmail.text = user.email
            self.textFirstName.text = user.firstname
            self.textLastName.text = user.lastname
            
            if let date = user.date(forKey: "dateOfBirth") {
                self.textDateOfBirth.text = MFDateFormatter.shared().string(from: date, isTimestamp: false)
            }
            self.textHeight.text = "\(user.double(forKey: "height"))"
            self.textWeight.text = "\(user.integer(forKey: "weight"))"
            self.switchIsMarried.isOn = user.boolean(forKey: "isMarried")
        }
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // update profile
        if indexPath.section == 2 && indexPath.row == 0 {
            let email = self.textEmail.text
            let firstname = self.textFirstName.text
            let lastname = self.textLastName.text
            
            let dateOfBirth = self.textDateOfBirth.text
            let height = self.textHeight.text
            let weight = self.textWeight.text
            let isMarried = self.switchIsMarried.isOn
            
            if let user = MFUser.currentUser() {
                // set required field
                user.email = email
                user.firstname = firstname
                user.lastname = lastname
                // set custom field
                if let date = MFDateFormatter.shared().date(from: dateOfBirth!) {
                    user["dateOfBirth"] = date
                }
                user["height"] = Double(height!)
                user["weight"] = Int(weight!)
                user["isMarried"] = isMarried
                // update user data async
                user.saveAsync(block: { (succeeded, error) in
                    if let e = error as? NSError {
                        self.showError(title: "Failed to update profile", error: e)
                        return
                    }
                    
                    self.showAlert(title: "Profile updated", message: "Your profile's has been successfully updated.")
                })
            }
        } // change password
        else if indexPath.section == 4 && indexPath.row == 0 {
            let oldPassword = self.textOldPassword.text
            let newPassword = self.textNewPassword.text
            let confirmPassword = self.textConfirmPassword.text
            
            if oldPassword == newPassword {
                self.showAlert(message: "Old and new password are equal.")
                return
            }
            
            if newPassword != confirmPassword {
                self.showAlert(message: "new and confirm password are not equal.")
                return
            }
            
            if let user = MFUser.currentUser() {
                user.changePasswordAsync(withOldPassword: oldPassword!, newPassword: newPassword!, block: { (succeeded, error) in
                    if let e = error as? NSError {
                        self.showError(title: "Failed to change password", error: e)
                        return
                    }
                    
                    self.showAlert(message: "Password changed successfully.")
                })
            }
        }
    }
}

Kesimpulan

Anda sudah berhasil membuat fetch danupdate data user untuk mobile aplikasi iOS. Semoga tutorial ini membantu teman-teman Codepolitan yang ingin mengembangkan project di iOS Mobile Apps. Last but not least, kalian tetap harus rajin praktik. Karena semakin serik kalian berlatih, kemampuan membangun mobile apps kalian juga semakin mahir.

Dilihat kali

Is this helpful?

Share This Post