Proper way to Encode and Send String as a PFObject - ios

I'm having an issue sending a string to Parse. Here's the line where the code stops:
Here's what my code looks like:
var friends: Array<AnyObject>?
var recipients: NSMutableArray?
var message: String!
var sendMessage:String!
override func viewDidLoad() {
super.viewDidLoad()
sendMessage = message
friends = []
recipients = []
let editButton = UIBarButtonItem(title: "Edit", style: UIBarButtonItemStyle.Plain, target: self, action: "edit")
navigationItem.rightBarButtonItem = editButton
tableView = UITableView(frame: view.bounds, style: UITableViewStyle.Plain)
tableView?.delegate = self
tableView?.dataSource = self
view.addSubview(tableView!)
let sendButton = [UIBarButtonItem(title: "Send", style: .Done, target: self, action: "sendPressed")]
toolbar.frame = CGRectMake(0, self.view.frame.size.height - 46, self.view.frame.size.width, 48)
toolbar.sizeToFit()
toolbar.setItems(sendButton, animated: true)
self.view.addSubview(toolbar)
}
func sendPressed () {
sendMessagetoParse()
}
func sendMessagetoParse(){
let messageString = message
let data = messageString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)! as NSData
// NSConcreteMutableData
let file = PFFile(name:message, data:data)
file.saveInBackground()
let sentMessage = PFObject(className:"Messages")
sentMessage["messages"] = file
sentMessage["username"] = PFUser.currentUser()?.username
sentMessage.setObject(self.recipients!, forKey: "recipientIds")
sentMessage.setObject(PFUser.currentUser()!.objectId!, forKey: "senderId")
sentMessage.setObject(PFUser.currentUser()!.username!, forKey: "senderName")
sentMessage.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if (success) {
println("Message sent!")
I want to send the string object to my parse account. I've also used the method Parse provides,, i.e. dataUsingEncoding(NSUTF8StringEncoding) but that is also returning the same error. Any clue on the proper format or how I need to fix the code?
EDIT:
Okay, I'm no longer getting the error, but my only issue is that once I press 'send', it doesn't do anything. Here's my edited code:
func sendMessagetoParse(){
let messageString = message
if messageString != nil
{
let data = messageString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)! as NSData
// NSConcreteMutableData
let file = PFFile(name:message, data:data)
file.saveInBackground()
let sentMessage = PFObject(className:"Messages")
sentMessage["messages"] = file
sentMessage["username"] = PFUser.currentUser()?.username
sentMessage.setObject(self.recipients!, forKey: "recipientIds")
sentMessage.setObject(PFUser.currentUser()!.objectId!, forKey: "senderId")
sentMessage.setObject(PFUser.currentUser()!.username!, forKey: "senderName")
sentMessage.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if (success) {
println("Message sent!")
var alert = UIAlertController(title: "Awesome!", message: "Message was Sent", preferredStyle: UIAlertControllerStyle.Alert);
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Cancel, handler: nil));
//show it
self.navigationController?.popToRootViewControllerAnimated(true)
} else {
println("error")
}
}
}
}
Here's code from the previous view controller, called ConfirmViewController, in which I tried to use a segue to pass a text label into the messageString into the current view controller, which is called FriendsViewController:
override func prepareForSegue(segue: (UIStoryboardSegue!), sender:
AnyObject!) {
if (segue.identifier == "addFriends") {
var mvc = segue!.destinationViewController as!
FriendsViewController;
mvc.sendMessage = messageView.text
}
}
With the segue set up in the ConfirmViewController I then set sendMessage equal to message in the viewDidLoad, as shown in my first edit.

Check your
let messageString
value. This runtime error you've got is probably a result of implicitly unwrapping optional value that is nil. You would want to execute your code inside an if statement like:
if let messageString != nil
{
////put your saving code here
}

Try this:
override func viewDidLoad() {
super.viewDidLoad()
// sendMessage = message
message = sendMessage

Related

Uploading an Image with Firebase & Swift (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
})
}
}

Model class gets the object but doesn't fulfill the TableView

I know this is a common problem but I can't find the solution whether I searched for hours so I decided to open a new question. I'm getting "[UIRefreshControl copyWithZone:]: unrecognized selector sent to instance 0x102029400" problem. When I first open the view. Loading appears but It doesn't fulfill the table. However when I check model class, It gets the values from database.
In viewcontroller declaration;
model.delegate = self
model.refresh_history(sensor_name: send_item)
// Set up a refresh control.
mTableView.refreshControl = UIRefreshControl()
mTableView.refreshControl?.addTarget(model, action: #selector(model.refresh_history), for: .valueChanged)
Delegate;
extension ChooseHistoryViewController: ModelDelegate {
func modelUpdated() {
mTableView.refreshControl?.endRefreshing()
mTableView.reloadData()
}
func errorUpdating(_ error: NSError) {
let message: String
if error.code == 1 {
message = "Error"
} else {
message = error.localizedDescription
}
let alertController = UIAlertController(title: nil,
message: message,
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
}
and my model class;
protocol ModelDelegate {
func errorUpdating(_ error: NSError)
func modelUpdated()
}
class Model{
var user: User
static let sharedInstance = Model()
var sensor_ecg: Sensor_ECG?
var delegate: ModelDelegate?
var history: [String] = []
init()
{
user = User()
}
#objc func refresh_history(sensor_name: String){
let parameters: Parameters = ["q" : "{\"member_id\" :\"\(user.id!)\"}", "apiKey": "2ABdhQTy1GAWiwfvsKfJyeZVfrHeloQI"]
Alamofire.request("https://api.mlab.com/api/1/databases/mysignal/collections/\(sensor_name)", method: .get, parameters: parameters,encoding: URLEncoding.default, headers: nil).responseJSON{ response in
let json = JSON(data: response.data!)
print(json)
if(response.response == nil) {
return
}
let history = json[0]["date"].string!
print(history)
}
DispatchQueue.main.async {
self.delegate?.modelUpdated()
}
}
You need to change
If you declared your method as "refresh_history:" (i.e. with a parameter), you need to add a colon to the "#selector" bit.
In other words, one line changes with one character:
mTableView.refreshControl?.addTarget(model, action: #selector(model.refresh_history(sensor_name:)), for: .valueChanged)

Parsing JSON Tableview Information as Separate Strings

I am currently trying to use information in Tableview cells that I have populated with JSON to execute various operations but I am unable to call the specific information due to the fact that it isn't in individual strings. Is there any way to take the group of data I have pulled into each tableview cell and turn it into a series of individual strings? Here is what I currently have:
import UIKit
import GoogleMobileAds
class OngoingViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var userUsernameLabel: UILabel!
#IBOutlet weak var bannerView: GADBannerView!
#IBOutlet weak var ongoingTable: UITableView!
var list:[MyStruct] = [MyStruct]()
struct MyStruct
{
var user1 = ""
var user2 = ""
var wager = ""
var amount = ""
init(_ user1:String, _ user2:String, _ wager:String, _ amount:String)
{
self.user1 = user1
self.user2 = user2
self.wager = wager
self.amount = amount
}
}
override func viewDidLoad() {
super.viewDidLoad()
let username = UserDefaults.standard.string(forKey: "userUsername")!
userUsernameLabel.text = username
/// The banner view.
print("Google Mobile Ads SDK version: " + GADRequest.sdkVersion())
bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
bannerView.rootViewController = self
bannerView.load(GADRequest())
ongoingTable.dataSource = self
ongoingTable.delegate = self
get_data("http://cgi.soic.indiana.edu/~team10/ongoingWagers.php")
}
func get_data(_ link:String)
{
let url:URL = URL(string: link)!
var request = URLRequest(url:url);
request.httpMethod = "POST";
let postString = "a=\(userUsernameLabel.text!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
self.extract_data(data)
}
task.resume()
}
func extract_data(_ data:Data?)
{
let json:Any?
if(data == nil)
{
return
}
do{
json = try JSONSerialization.jsonObject(with: data!, options: [])
}
catch
{
return
}
guard let data_array = json as? NSArray else
{
return
}
for i in 0 ..< data_array.count
{
if let data_object = data_array[i] as? NSDictionary
{
if let data_user1 = data_object["id"] as? String,
let data_user2 = data_object["id2"] as? String,
let data_wager = data_object["wager"] as? String,
let data_amount = data_object["amount"] as? String
{
list.append(MyStruct(data_user1, data_user2, data_wager, data_amount))
}
}
}
refresh_now()
}
func refresh_now()
{
DispatchQueue.main.async(
execute:
{
self.ongoingTable.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return list.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.ongoingTable.dequeueReusableCell(withIdentifier: "owcell", for: indexPath) as! OngoingTableViewCell
cell.infoLabel.text = list[indexPath.row].user1 + " " + list[indexPath.row].user2 + " " + list[indexPath.row].wager + " " + list[indexPath.row].amount
cell.user1Button.tag = indexPath.row
cell.user1Button.addTarget(self, action: #selector(OngoingViewController.user1Action), for: .touchUpInside)
cell.user2Button.tag = indexPath.row
cell.user2Button.addTarget(self, action: #selector(OngoingViewController.user2Action), for: .touchUpInside)
return cell
}
#IBAction func user1Action(sender: UIButton) {
let user1Alert = UIAlertController(title: "Wait a second!", message: "Are you sure this user has won this wager?", preferredStyle: UIAlertControllerStyle.alert)
user1Alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: { action in
let user1ConfirmationAlert = UIAlertController(title: "Great!", message: "Please wait for the other user to confirm the winner of this wager.", preferredStyle: UIAlertControllerStyle.alert)
user1ConfirmationAlert.addAction(UIAlertAction(title: "Got It!", style: UIAlertActionStyle.default, handler: nil))
self.present(user1ConfirmationAlert, animated: true, completion: nil)
}))
user1Alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.default, handler: nil))
self.present(user1Alert, animated: true, completion: nil)
}
#IBAction func user2Action(sender: UIButton) {
let user2Alert = UIAlertController(title: "Wait a second!", message: "Are you sure this user has won this wager?", preferredStyle: UIAlertControllerStyle.alert)
user2Alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: { action in
let user2ConfirmationAlert = UIAlertController(title: "Great!", message: "Please wait for the other user to confirm the winner of this wager.", preferredStyle: UIAlertControllerStyle.alert)
user2ConfirmationAlert.addAction(UIAlertAction(title: "Got It!", style: UIAlertActionStyle.default, handler: nil))
self.present(user2ConfirmationAlert, animated: true, completion: nil)
}))
user2Alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.default, handler: nil))
self.present(user2Alert, animated: true, completion: nil)
}
}
Here is the OngoingTableViewCell subclass:
import UIKit
class OngoingTableViewCell: UITableViewCell {
#IBOutlet weak var infoLabel: UILabel!
#IBOutlet weak var user1Button: UIButton!
#IBOutlet weak var user2Button: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
You have an array of MyStruct structures, that contain entries for user1, user1, wager, and amount. That's good.
You're using tags on the buttons as a way of figuring out the selected cell, which is not ideal. Instead I would suggest using the sender parameter to figure out the indexPath of the cell that contains the button. See the bottom of my answer for the details of a better way to do it.
In any case, once you have a row number, you can easily get to the data for that wager by indexing into your array:
#IBAction func user1Action(sender: UIButton) {
selectedRow = sender.tag
//or, using my function:
selectedRow = tableView.indexPathForView(sender)
//Get the wager for the button the user tapped on.
let thisWager = list[selectedRow]
}
If you want to take action on the wager once the user taps a button in your UIAlertController, don't use a nil handler on the your second alert controller. Instead, pass in a closure that uses the selectedRow parameter from the code above to index into the list of wagers, or even use the thisWager local variable I show in my code.
Getting the indexPath of the button the user taps on:
I created a simple extension to UITableView that lets you pass in a UIView (like the sender from a button action) and get back the indexPath that contains that view.
That extension is dirt-simple. Here's how it looks:
public extension UITableView {
/**
This method returns the indexPath of the cell that contains the specified view
- Parameter view: The view to find.
- Returns: The indexPath of the cell containing the view, or nil if it can't be found
*/
func indexPathForView(_ view: UIView) -> IndexPath? {
let origin = view.bounds.origin
let viewOrigin = self.convert(origin, from: view)
let indexPath = self.indexPathForRow(at: viewOrigin)
return indexPath
}
}
And you can call that function from your button's actions:
#IBAction func buttonTapped(_ button: UIButton) {
if let indexPath = self.tableView.indexPathForView(button) {
print("Button tapped at indexPath \(indexPath)")
}
else {
print("Button indexPath not found")
}
}
The whole project can be found on Github at this link: TableViewExtension

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