Uploading an Image with Firebase & Swift (iOS) - ios

Before I start, I would just like to pre-warn that my code is most likely not correct due to me being a beginner at coding with Swift.
I am creating an app for a university project, it is the first large app that I have created and I haven't been coding for very long.
I am having a problem when trying to upload an image whilst creating an account with firebase, I have had the code working previously but I was writing to the database with 'childByAutoId()' which was working fine, however I realised that I needed to be writing to the database and saving it by the users ID instead. After I changed 'childByAutoId()' to 'child(uid)' which is my prefixed variable for the users ID it stopped uploading the images and I can't figure out why. I have tried to go back to when it was working with childByAutoId() but now that isn't working either.
My code:
import UIKit
import Firebase
import FirebaseStorage
class RegisterViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var dobField: UITextField!
#IBOutlet weak var selectImageButton: UIButton!
var imageFileName = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))
let datePicker = UIDatePicker()
datePicker.datePickerMode = UIDatePickerMode.date
datePicker.addTarget(self, action: #selector(RegisterViewController.datePickerValueChanged(sender:)), for: UIControlEvents.valueChanged)
dobField.inputView = datePicker
self.profileImage.layer.cornerRadius = self.profileImage.frame.size.width / 2;
self.profileImage.clipsToBounds = true;
}
#objc func datePickerValueChanged(sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.medium
formatter.timeStyle = DateFormatter.Style.none
dobField.text = formatter.string(from: sender.date)
}
#IBAction func selectImageTapped(_ sender: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self
self.present(picker, animated: true, completion: nil)
}
func uploadImage(image: UIImage) {
let randomName = randomStringWithLength(length: 10)
let imageData = UIImageJPEGRepresentation(image, 1.0)
let uploadRef = Storage.storage().reference().child("images/profimg/\(randomName).jpg")
let uploadTask = uploadRef.putData(imageData!, metadata: nil) { metadata,
error in
if error == nil {
//success
print("success")
self.imageFileName = "\(randomName as String).jpg"
} else {
//error
print("error uploading image")
}
}
}
func randomStringWithLength(length: Int) -> NSString {
let characters: NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let randomString: NSMutableString = NSMutableString(capacity: length)
for i in 0..<length {
var len = UInt32(characters.length)
var rand = arc4random_uniform(len)
randomString.appendFormat("%C", characters.character(at: Int(rand)))
}
return randomString
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// will run if the user hits cancel
picker.dismiss(animated: true, completion: nil)
}
#objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// will run when the user finishes picking an image from the library
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.profileImage.image = pickedImage
self.selectImageButton.isEnabled = false
self.selectImageButton.isHidden = true
uploadImage(image: pickedImage)
picker.dismiss(animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func registerTapped(_ sender: UIButton) {
let username = usernameField.text
let email = emailField.text
let password = passwordField.text
let dob = dobField.text
Auth.auth().createUser(withEmail: email!, password: password!) { (user, error) in
if error != nil {
//error creating account
let alert = UIAlertController(title: "Error", message: "An error occurred when creating your account, please try again.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}else {
//account created
if (self.imageFileName != "") {
if let uid = Auth.auth().currentUser?.uid {
let regObject: Dictionary<String, Any> = [
"uid" : uid,
"username" : username,
"dateofbirth" : dob,
"profimage" : self.imageFileName
]
Database.database().reference().child("posts").child(uid).setValue(regObject)
let vc = self.storyboard?.instantiateViewController(withIdentifier: "LoggedInVC")
self.present(vc!, animated: true, completion: nil)
}else {
//image hasnt finished uploading
let alert = UIAlertController(title: "Please wait", message: "Your image has not finished uploading yet, please wait...", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
//let alert = UIAlertController(title: "Success!", message: "Account has been created...", preferredStyle: .alert)
//alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
//self.present(alert, animated: true, completion: nil)
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
If any of you can point me in the right direction or be able to show me where I have gone wrong within my code that would be great. I am not expected a direct solution to my problem so anything will help.
Thank you!

To upload img on firebase storage
func uploadImagePic(img1 :UIImage){
var data = NSData()
data = UIImageJPEGRepresentation(img1!, 0.8)! as NSData
// set upload path
let filePath = "\(userid)" // path where you wanted to store img in storage
let metaData = FIRStorageMetadata()
metaData.contentType = "image/jpg"
self.storageRef = FIRStorage.storage().reference()
self.storageRef.child(filePath).put(data as Data, metadata: metaData){(metaData,error) in
if let error = error {
print(error.localizedDescription)
return
}else{
//store downloadURL
let downloadURL = metaData!.downloadURL()!.absoluteString
}
}
}

In order to get the download url from the uploaded file, based on the answer, downloadURL from metaData is now deprecated, so this is the proper way:
storageRef.downloadURL(completion: { (url: URL?, error: Error?) in
print(url?.absoluteString) // <- Your url
})
You should get the download url from the reference that you just created, where you can find the downloadURL with a completion handler.
This is an updated Swift 5 answer:
func uploadImagePic(image: UIImage, name: String, filePath: String) {
guard let imageData: Data = image.jpegData(compressionQuality: 0.1) else {
return
}
let metaDataConfig = StorageMetadata()
metaDataConfig.contentType = "image/jpg"
let storageRef = Storage.storage().reference(withPath: filePath)
storageRef.putData(imageData, metadata: metaDataConfig){ (metaData, error) in
if let error = error {
print(error.localizedDescription)
return
}
storageRef.downloadURL(completion: { (url: URL?, error: Error?) in
print(url?.absoluteString) // <- Download URL
})
}
}

Related

How to Crop iPhone Image in Swift 3 App

I am currently in the process of creating a camera app, however when someone takes a picture and it goes to the the crop screen, it doesn't actually fit it to that specific size. How can I change my code to make it only spit out a 800x800 image?
import UIKit
import Firebase
class CameraControllerViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var postBtn: UIButton!
#IBOutlet weak var pickedimage: UIImageView!
#IBOutlet weak var libBtn: UIButton!
#IBOutlet weak var camBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func camerabuttonaction(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
imagePicker.allowsEditing = false
self.present(imagePicker, animated:true, completion: nil)
}
}
#IBAction func photolibraryaction(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
#IBAction func saveaction(_ sender: Any) {
let imageData = UIImageJPEGRepresentation(pickedimage.image!, 0.6)
let compressedJPEGImage = UIImage(data: imageData!)
UIImageWriteToSavedPhotosAlbum(compressedJPEGImage!, nil, nil, nil)
saveNotice()
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]! ) {
pickedimage.image = image
camBtn.isHidden = true
libBtn.isHidden = true
postBtn.isHidden = false
self.dismiss(animated: true, completion: nil);
}
func saveNotice() {
AppDelegate.instance().showActivityIndicator()
//let alertController = UIAlertController(title: "Image Saved", message: "Your picture was saved.", preferredStyle: .alert)
//let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
//alertController.addAction(defaultAction)
//present(alertController, animated: true, completion: nil)
let uid = Auth.auth().currentUser!.uid
let ref = Database.database().reference()
let storage = Storage.storage().reference(forURL: "gs://new-glaance.appspot.com")
let key = ref.child("posts").childByAutoId().key
let imageRef = storage.child("posts").child(uid).child("\(key).jpg")
let data = UIImageJPEGRepresentation(self.pickedimage.image!, 0.6)
let uploadTask = imageRef.putData(data!, metadata: nil) { (metadata,error) in
if error != nil {
print(error!.localizedDescription)
AppDelegate.instance().dismissActivityIndicator()
return
}
imageRef.downloadURL(completion: { (url, error) in
if let url = url {
let feed = ["userID": uid,
"pathToImage": url.absoluteString,
"likes":0,
"author": Auth.auth().currentUser!.displayName!,
"postID": key] as [String: Any]
let postFeed = ["\(key)":feed]
ref.child("posts").updateChildValues(postFeed)
AppDelegate.instance().dismissActivityIndicator()
}
})
}
uploadTask.resume()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
I don't know of a way to constrain a crop to a particular aspect ratio. Instead I'd suggest creating your own method for cropping images.
I have an app on Github called CropImg that does just that. It doesn't constrain the crop to square, but that would be easy to add.

Profile page swift 3 errors

This is the code that I have created for my profile page but it has some mistakes that i would like to adjust.
import UIKit
import FirebaseStorage
import FirebaseDatabase
import FirebaseAuth
import Firebase
class ProfileClass: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var userImagePicker: RoundButton!
#IBOutlet weak var ProfilePicture: RoundImage!
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var imageLoader: UIActivityIndicatorView!
var loggedInUser = AnyObject?()
var databaseRef = FIRDatabase.database().reference()
var storageRef = FIRStorage.storage().reference()
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
self.loggedInUser = FIRAuth.auth()?.currentUser
self.databaseRef.child("user_profile").child(self.loggedInUser!.uid).observeSingleEvent(of: FIRDataEventType(.Value) { (snapshot:FIRDataSnapshot) in
if(snapshot.value!["usernameField"] !== nil) {
self.usernameField.text = snapshot.value!["usernameField"] as? String
}
if(snapshot.value!["profile_pic"] !== nil) {
let databaseProfilePic = snapshot.value!["profile_pic"]
as! String
let data = NSData(contentsOfURL: NSURL(string: databaseProfilePic)!)
self.setProfilePicture(self.ProfilePicture,imageToSet:UIImage(data:data!)!)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func logoutTapped(_ sender: Any) {
let firebaseAuth = FIRAuth.auth()
do {
try firebaseAuth?.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %#", signOutError)
}
self.performSegue(withIdentifier: "goToLogin", sender: self)
}
#IBAction func TapProfileButton(_ sender: RoundButton) {
let myActionShett = UIAlertController(title:"Profile Picture",message:"Select",preferredStyle: UIAlertControllerStyle.actionSheet)
let viewPicture = UIAlertAction(title: "View Picture", style: UIAlertActionStyle.default) { (action) in
let imageView = sender.view as! RoundImage
let newImageView = RoundImage(image: imageView.image)
newImageView.frame = self.view.frame
newImageView.backgroundColor = UIColor.blackColor()
newImageView.contentMode = .scaleAspectFit
newImageView.userInteractionEnabled = true
let tap = UITapGestureRecognizer(target:self,action:#selector(self.dismissFullScreenImage))
newImageView.addGestureRecognizer(tap)
self.view.addSubview(newImageView)
}
let photoGallery = UIAlertAction(title: "Photos", style: UIAlertActionStyle.default) { (action) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum)
{
self.imagePicker.delegate = self
self.imagePicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum
self.imagePicker.allowsEditing = true
self.present(self.imagePicker, animated: true, completion: nil)
}
}
let camera = UIAlertAction(title: "Camera", style: UIAlertActionStyle.default)
{ (action) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
{
self.imagePicker.delegate = self
self.imagePicker.sourceType = UIImagePickerControllerSourceType.camera
self.imagePicker.allowsEditing = true
self.present(self.imagePicker, animated: true, completion: nil)
}
}
myActionShett.addAction(viewPicture)
myActionShett.addAction(photoGallery)
myActionShett.addAction(camera)
myActionShett.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
self.present(myActionShett, animated: true, completion: nil)
}
func dismissFullScreenImage(sender:UITapGestureRecognizer)
{
sender.view?.removeFromSuperview()
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
self.imageLoader.stopAnimating()
setProfilePicture(self.ProfilePicture,imageToSet: image)
if let imageData: NSData = UIImagePNGRepresentation(self.ProfilePicture, image!)!
{
let profilePicStorageRef = storageRef.child("user_profiles/\(self.loggedInUser!.uid)/profile_pic")
let uploadTask = profilePicStorageRef.putData(imageData, metadata: nil)
{metadata,error in
if(error == nil)
{
let downloadUrl = metadata!.downloadUrl()
self.databaseRef.child("user_profile").child(self.loggedInUser!.uid).child("profile_pic").setValue(downloadUrl!.absoluteString)
}
else
{
print(error?.localizedDescription)
}
self.imageLoader.stopAnimating()
}
}
self.dismiss(animated: true, completion: nil)
}
}
You have to give proper type. You can not initialize object of type AnyObject. and Obviously with not using AnyObject?.

Unresolved identifier error 'email'

This is related to a previous question that was solved (See here: Sharing variables). I saw nothing that addresses what to do if your variable still isn't being recognized but your code to pass the variable appears solid.
I'm getting an unresolved identifier error 'email' when attempting to utilize a user's email address as part of a file path to upload an image to Firebase Storage. Code is here:
import UIKit
import Firebase
import MobileCoreServices
import FirebaseStorage
class ThirdViewController: UIViewController {
#IBOutlet weak var uploadButton: UIButton!
#IBOutlet weak var progressView: UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named:"Book Funnel")!)
// Do any additional setup after loading the view.
}
#IBAction func uploadButtonWasPressed(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String, kUTTypeMovie as String]
imagePicker.delegate = self
self.present(imagePicker, animated: true, completion: nil)
}
func uploadImageToFirebaseStorage(data: NSData) {
let storageRef = FIRStorage.storage().reference(withPath: email/"/image.jpg")
let uploadMetadata = FIRStorageMetadata()
uploadMetadata.contentType = "image/jpeg"
let uploadTask = storageRef.put(data as Data, metadata: uploadMetadata) { (metadata, error) in
_ = metadata?.downloadURL
if (error != nil) {
print("I recieved an error! \(error?.localizedDescription)")
} else {
print ("Upload complete! Here's some metadata! \(metadata)")
}
let alert = UIAlertController(title: "Success!", message: "Image uploaded", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "okay", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
uploadTask.observe(.progress) { [weak self] (snapshot) in
guard let strongSelf = self else { return }
guard let progress = snapshot.progress else { return }
strongSelf.progressView.progress = Float(progress.fractionCompleted)
}
}
var toPass: String!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension ThirdViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let mediaType: String = info[UIImagePickerControllerMediaType] as? String else {
dismiss(animated: true, completion: nil)
return
}
if mediaType == (kUTTypeImage as String) {
if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage, let imageData = UIImageJPEGRepresentation(originalImage, 0.8) {
uploadImageToFirebaseStorage(data: imageData as NSData)
}
} else {
print("Please select an image")
}
dismiss(animated: true, completion: nil)
func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "segueTest") {
//Checking identifier is crucial as there might be multiple
// segues attached to same view
if let fourthVC = segue.destination as? FourthViewController {
fourthVC.toPass = "email"
}
}
}
}
}

How do I add an avatar when signing up a user with Parse (Swift 3)

I have a function which successfully adds a user to the User table in my Parse class, but I want to add an avatar to the signup form.
The stoyboard side of things is working fine, and I can select and image from the camera or photo library and add it to my imageView (profilePic) but when I try to add this to the signUpInBackground method, it crashes the app.
I am a complete newb to ios development, but am familiar with other coding languages so it's not all completely foreign, I just don't know what I am missing here or whether it's just not possible to add an image at signup?
Help!
let user = PFUser()
user.email = emailAddress.text
user.username = screenName.text
user.password = password.text
let image = self.profilePic.image
if image != nil {
let imagedata = UIImagePNGRepresentation(image!)!
let file = PFFile(name: "image.png", data: imagedata)
user["profilePic"] = file
}
user.signUpInBackground(block: { (success, error) in
if error != nil {
// error code
} else {
// user logged in successfully
}
}
}
Here is what you can do. I added validation for to it as well. Also i created it that once successful signup, log the user then in. You can remove that if you don't want it. This is a swift3 example!
#IBOutlet weak var avatarImage: UIImageView!
#IBOutlet var emailAddress: UITextField!
#IBOutlet var password: UITextField!
// MARK: - UPLOAD AVATAR BUTTON
#IBAction func uploadAvatarButt(_ sender: AnyObject) {
let alert = UIAlertController(title: APP_NAME,
message: "Select source",
preferredStyle: .alert)
let camera = UIAlertAction(title: "Take a picture", style: .default, handler: { (action) -> Void in
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
})
let library = UIAlertAction(title: "Pick from library", style: .default, handler: { (action) -> Void in
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
})
// Cancel button
let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: { (action) -> Void in })
alert.addAction(camera)
alert.addAction(library)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
// ImagePicker delegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
avatarImage.image = image
}
dismiss(animated: true, completion: nil)
}
// MARK: - SIGNUP BUTTON
#IBAction func signupButt(_ sender: AnyObject) {
if password.text == "" || emailAddress.text == "" || screenName.text == "" {
//You can alert here , that fields need to be filled.
} else {
let userForSignUp = PFUser()
userForSignUp.username = screenName.text!.lowercased()
userForSignUp.password = password.text
userForSignUp.email = emailAddress.text
if avatarImage.image != nil {
let imageData = UIImageJPEGRepresentation(avatarImage.image!, 0.8)
let imageFile = PFFile(name:"image.jpg", data:imageData!)
// profilePic needs to be the name of the col
userForSignUp["profilePic"] = imageFile
}
userForSignUp.signUpInBackground { (succeeded, error) -> Void in
if error == nil {
//Signup Success
PFUser.logInWithUsername(inBackground: self.screenName.text!, password:self.password.text!) { (user, error) -> Void in
if error == nil {
//Login Success
} else {
//Login Falied
}}
// ERROR
} else {
//Signup Failed
}}
}
}

How can I Store the Token in NSUserDefault while using Alamofire?

I am making Email verification using OTP . I have used two API , one for registration and other for OTP verification. I want to move on the next page when user is valid. For this , I want to use NSUserDefault to store the token from the API response. When , I use this , i am unable to store this . Please anybody help me for this.
Here is my code
class OTPVerification: UIViewController, UITextFieldDelegate {
#IBOutlet weak var tfReceivedOTP: UITextField!
var datapassed:String!
let loader = MFLoader()
override func viewDidLoad() {
super.viewDidLoad()
tfReceivedOTP.attributedPlaceholder = NSAttributedString(string:"OTP",
attributes:[NSForegroundColorAttributeName: UIColor.whiteColor()])
tfReceivedOTP.delegate = self
print(datapassed)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.objectForKey("email") == nil {
if let loginController = self.storyboard?.instantiateViewControllerWithIdentifier("ConfirmationMassage") as? SignInConformation {
self.navigationController?.presentViewController(loginController, animated: true, completion: nil)
}
}
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.objectForKey("token") == nil {
if let loginController = self.storyboard?.instantiateViewControllerWithIdentifier("ConfirmationMassage") as? SignInConformation {
self.navigationController?.presentViewController(loginController, animated: true, completion: nil)
}
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func prefersStatusBarHidden() -> Bool {
return true
}
#IBAction func btnOTPVerificationTapped(sender: AnyObject) {
loader.showActivityIndicator(self.view)
let rgModel = CAOTPVerify()
rgModel.email = datapassed!
rgModel.otpPassword = tfReceivedOTP.text!
rgModel.otpRegister({(Void, Any) -> Void in
let defaults = NSUserDefaults.standardUserDefaults()
if let name = defaults.stringForKey("userNameKey") {
print("\(name )hjhjkhkhkh")
}
self.loader.hideActivityIndicator(self.view)
if let response = Any as? [String : AnyObject] {
//print(response)
if let messgae = response["message"] as? String {
let alert = UIAlertController(title: "Alert", message: messgae, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {action in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let OPTView = storyboard.instantiateViewControllerWithIdentifier("sideBarMenu") as! SideBarMenu
self.navigationController!.pushViewController(OPTView, animated: true)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
}, errorCallback: {(Void, NSError) -> Void in
self.loader.hideActivityIndicator(self.view)
})
}
You didnt posted the code to save a string to the NSUserDefaults. You can refer following code to save a string in NSUserDefaults
let myString = "Hello World"
NSUserDefaults.standardUserDefaults().setObject(myString, forKey: "myKey")

Resources