0

I have created a register page in which there are username,password,confirm password,email id, mobile no. these are the details ,I am new to Swift and i want to save user details for register page in Application using NSUserDefaultspls help me and also how to post request .

shallowThought
  • 19,212
  • 9
  • 65
  • 112
  • 1
    Do Not, Do Not, Do Not store passwords in UserDefaults, that's what the keychain is for. Tell me what apps you've done this for and I'll make sure I don't use them. – Abizern Aug 06 '17 at 10:35
  • 3
    Possible duplicate of [iOS: How to store username/password within an app?](https://stackoverflow.com/questions/6972092/ios-how-to-store-username-password-within-an-app) – Abizern Aug 06 '17 at 10:37
  • ok @Abizern i will do –  Aug 06 '17 at 17:12

2 Answers2

0

To set data in UserDefaults-

UserDefaults.standard.set("your value", forKey: "your key")
UserDefaults.standard.synchronize()

To get data in UserDefaults

UserDefaults.standard.value(forKey: "your key")

Post Example

func postAction(_ sender: Any) {
        let Url = String(format: "your url")
        guard let serviceUrl = URL(string: Url) else { return }
        //        let loginParams = String(format: LOGIN_PARAMETERS1, "test", "Hi World")
        let parameterDictionary = ["username" : "Test", "password" : "123456"]
        var request = URLRequest(url: serviceUrl)
        request.httpMethod = "POST"
        request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
        guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
            return
        }
        request.httpBody = httpBody

        let session = URLSession.shared
        session.dataTask(with: request) { (data, response, error) in
            if let response = response {
                print(response)
            }
            if let data = data {
                do {
                    let json = try JSONSerialization.jsonObject(with: data, options: [])
                    print(json)
                }catch {
                    print(error)
                }
            }
            }.resume()
    }
Abhishek Jain
  • 4,557
  • 2
  • 32
  • 31
  • Don't forget to add `UserDefaults.standard.synchronize()` after set values to `UserDefault` – Kavin Kumar Arumugam Aug 05 '17 at 06:07
  • can u tell me how to save using all details of register page in NSObject class and how to use in a particular class @Abhishek Jain –  Aug 05 '17 at 06:10
-1

TO save data

 UserDefaults.standard.set(username, forKey: "username")
 UserDefaults.standard.synchronize()

To get data

  UserDefaults.standard.value(forKey: "username")     

To post data you can use Alamofire

Create a pod file add

     pod 'Alamofire', '~> 4.0'

In your viewcontroller

 import Alamofire

Create func

 funcLogin() {


    let url = "http://example.com"

    let parameters : [String:Any] = ["username": UserDefaults.standard.value(forKey: "username")  as! String,
                                     "password": UserDefaults.standard.value(forKey: "password")  as! String,
                                     "email":UserDefaults.standard.value(forKey: "email")  as! String]


    Alamofire.request(url,method:.post, parameters: parameters).validate(contentType: ["application/json"])
        .responseJSON{ response in


            switch response.result {
            case .success:

                let statusCode = (response.response?.statusCode)!
                print("HTTP code @apiGetUser: \(statusCode)")
                print("yoo")
                print(response.result.value! )



                // ...

            case .failure(let error):
                print(error)
                //   print("yo")
                break
                // ...
            }

    }

You can also use this

Make extention of uiviewcontroller

     extension UIViewController{


      class user {


    var user_name : String
    var user_Email : String
    var user_password : String
    var item_Mobile : String

    init(user_name : String, user_Email : String, user_password : String, item_Mobile : String) {


        self.user_name = user_name
        self.user_Email = user_Email
        self.user_password = user_password

        self.item_Mobile = item_Mobile




    }


}

In ViewController

           var userData = [user]()

if to want to access globally

          static  var userData = [user]()

To Add values use

//For local

        userData.append(cartItem(user_name: "Demo1",
                                                    user_Email: "demo@demo.com",
                                                    user_password: "hhhhhhh",
                                                    item_Mobile: "9889878888"))

//For Using global

       viewControllername.userData.append(cartItem(user_name: "Demo1",
                                                    user_Email: "demo@demo.com",
                                                    user_password: "hhhhhhh",
                                                    item_Mobile: "9889878888"))

to access data

           userData[i]. user_name
Subhojit Mandal
  • 450
  • 4
  • 13
  • 1
    No, *to get data* in case of a string it's `.string(forKey:` for other objects `.object(forKey:` but **never** `.value(forKey:` – vadian Aug 05 '17 at 05:59
  • you can do like this UserDefaults.standard.value(forKey: "username") as! String – Subhojit Mandal Aug 05 '17 at 06:05
  • You can, but KVC methods have a special functionality. Use them only if you explicitly need KVC. With `UserDefaults` you don't need. – vadian Aug 05 '17 at 06:06
  • can u tell me how to save using all details of register page in NSObject class and how to use in a particular class @SubhojitMandal –  Aug 05 '17 at 06:11
  • first you have to save all vales from textfieds to userDefaults – Subhojit Mandal Aug 05 '17 at 06:13
  • UserDefaults.standard.set( yourtxtField.text! , forKey: "username") – Subhojit Mandal Aug 05 '17 at 06:13
  • can u tell me @SubhojitMandal if u have a sample code –  Aug 05 '17 at 06:14
  • i have only create design for register page now can u tell me steps to save details and post the request to web server @SubhojitMandal –  Aug 05 '17 at 06:15
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/151126/discussion-between-sunny-and-subhojit-mandal). –  Aug 05 '17 at 06:16