upload image swift through php to server - php

I followed a tutorial online to upload image to server from swift. I used his sample interface and everything looks fine except I'm getting error "Message":"Sorry, there was an error uploading your file.","Status":Error,"userId":"9". My codes are
<?php
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$userId = $_POST["userId"];
$target_dir = "percyteng.com/orbit/ios/image";if(!file_exists($target_dir))
{
mkdir($target_dir, 0777, true);
}
$target_dir = $target_dir . "/" . $_FILES["file"]["name"];
echo json_encode( $target_dir);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) {
echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK",
"userId" => $_REQUEST["userId"]
]);
} else {
echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error",
"userId" => $_REQUEST["userId"]
]);
}
?>
I have checked and the parameters did get passed from swift.
Here is my code in swift.
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
#IBOutlet weak var image: UIImageView!
#IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
#IBAction func selectImage(sender: AnyObject) {
let ImagePicker = UIImagePickerController()
ImagePicker.delegate = self
ImagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(ImagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
image.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func Upload(sender: AnyObject) {
myImageUploadRequest()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func myImageUploadRequest()
{
let myUrl = NSURL(string: "http://www.percyteng.com/orbit/ios/try.php");
//let myUrl = NSURL(string: "http://www.boredwear.com/utils/postImage.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let param = [
"firstName" : "Sergey",
"lastName" : "Kargopolov",
"userId" : "9"
]
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(image.image!, 1)
if(imageData==nil) { return; }
request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
// You can print out response object
print("******* response = \(response)")
// Print out reponse body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("****** response data = \(responseString!)")
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
dispatch_async(dispatch_get_main_queue(),{
// self.myActivityIndicator.stopAnimating()
self.image.image = nil;
});
/*
if let parseJSON = json {
var firstNameValue = parseJSON["firstName"] as? String
println("firstNameValue: \(firstNameValue)")
}
*/
}
task.resume()
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
var body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
let filename = "user-profile.jpg"
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
}
extension NSMutableData {
func appendString(string: String) {
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
appendData(data!)
}
}

Your iOS code works for me if I use move_uploaded_file() in the php script to move the image from the tempfile path to an existing dir on my server, so that I don't run into problems creating the dir (I also commented out the json conversion of the response). Therefore, the boundaries in the body of the request were all created correctly.
I suspect move_uploaded_file() is failing because of a directory problem. Try something like this:
if(!file_exists($target_dir))
{
mkdir($target_dir, 0777, true) or exit("Couldn't create $target_dir!");
}

Related

take photo from library and upload image to server swift 4

I am new to swift and tried many blog posts and github to take image from library and upload it to server(php server side). can you please write the code which takes photo from photo library and upload it to server using alamofire and any other method.
below is the code i was trying to upload photo from photolibrary
#IBAction func upload(_ sender: Any) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
picker.allowsEditing = false
self.present(picker, animated: true) {
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.image = originalImage
let image = UIImage.init(named: "\(originalImage)")
let imgData = UIImageJPEGRepresentation(image!, 0.2)!
let parameters = ["user":"Sol", "password":"secret1234"]
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
} //Optional for extra parameters
},
to:"website")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response.result.value)
}
case .failure(let encodingError):
print(encodingError)
}
}
}
self.dismiss(animated: true, completion: nil)
}
}
#IBAction func upload(_ sender: Any) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
picker.allowsEditing = false
self.present(picker, animated: true) {
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.image = originalImage
if let imgData = UIImageJPEGRepresentation(originalImage, 0.2) {
let parameters = ["user":"Sol", "password":"secret1234"]
upload(params: parameters, imageData: imgData)
}
}
picker.dismiss(animated: true, completion: nil)
}
func upload(params : [String: Any], imageData: Data) {
if let url = URL(string: "EnterUrl") {
Alamofire.upload(
multipartFormData: { (multipartdata) in
multipartdata.append(
imageData,
withName: "fileset",
fileName: String("\(Date().timeIntervalSince1970).jpg"),
mimeType: "image/jpg"
)
for (key,value) in params {
if let data = value as? String,
let data1 = data.data(using: .utf8)
{
multipartdata.append(
data1,
withName: key
)
}
}
},
to: url,
method: .post,
headers: nil,
encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON(completionHandler: { (response) in
if let err = response.error {
print(err.localizedDescription)
} else {
print(response.result.value ?? "No data")
}
})
case .failure(let error):
print(error.localizedDescription)
}
}
)
}
}
}
try this.

Swift 3 - Displaying images from mySQL database in newsfeed

So I'm in the middle of designing a social media application that displays posts, comprised of a picture and a description, on a newsfeed. I am able to upload posts to our database, however, I am having problems pulling the image from the database. Specifically, I am getting an error around the code
let image = post["path"] as! UIImage
Saying:
"Thread 1: signal SIGABRT", while the compiler says "Could not cast
value of type '__NSCFString' to 'UIImage'."
Here's the entirety of my code:
import UIKit
class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var activities = [AnyObject]()
var images = [UIImage]()
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//tableView.contentInset = UIEdgeInsetsMake(2, 0, 0, 0)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return activities.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "activity", for: indexPath) as! CustomCell
let post = activities[indexPath.row]
print(post["path"])
let image = post["path"] as! UIImage
let username = post["username"] as? String
let text = post["text"] as? String
cell.titleLbl.text = text
cell.userLbl.text = username
cell.activityImage.image = image //as! UIImage
//cell.dateLbl.text = activities[indexPath.row]
//cell.activityImage.image = images[indexPath.row]
DispatchQueue.main.async {
}
return cell
}
override func viewWillAppear(_ animated: Bool) {
loadActivities()
}
func loadActivities() {
let id = user!["id"] as! String
let url = URL(string: "https://cgi.soic.indiana.edu/~team7/posts.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let body = "id=\(id)&text=&uuid="
request.httpBody = body.data(using: String.Encoding.utf8)
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
if error == nil {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
// clean up
self.activities.removeAll(keepingCapacity: false)
self.images.removeAll(keepingCapacity: false)
//self.tableView.reloadData()
guard let parseJSON = json else {
print("Error while parsing")
return
}
guard let posts = parseJSON["posts"] as? [AnyObject] else {
print("Error while parseJSONing")
return
}
self.activities = posts
for i in self.activities.indices {
print("printed")
let path = self.activities[i]["path"] as? String
if let actualPath = path, !actualPath.isEmpty, let url = URL(string: actualPath) {
if let imageData = try? Data(contentsOf: url) {
if let image = UIImage(data: imageData) {
self.images.append(image)
print(self.images)
}
}
}
/*
if path != "" {
//let url = URL(string: path!)!
let url = URL(fileURLWithPath: path!)
let imageData = try? Data(contentsOf: url)
//let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!
self.images.append(image)
*/
else {
let image = UIImage()
self.images.append(image)
}
}
self.tableView.reloadData()
} catch {
}
} else {
}
})
}.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension NSMutableData {
func appendString(_ string : String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
append(data!)
}
}
If there is anything you think I should do to improve or make the code run correctly, please let me know!

Swift 3 - Pulling images from mySQL database

I am currently in the process of designing an application that has a newsfeed. Images and text are stored in our database but I am having trouble pulling the image and displaying it. The code I have should work but I am getting a fatal error saying "THREAD 1: EXC_BAD_INSTRUCTION" around
let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!
and the compiler displays this message - "fatal error: unexpectedly found nil while unwrapping an Optional value".
I'm getting the error in this snippet of code:
if!path!.isEmpty {
let url = URL(string: path!)!
let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!
self.images.append(image)
} else {
let image = UIImage()
self.images.append(image)
}
Being very new to programming, I've been stuck on this for quite a while now. If there is anything you suggest, let me know! Thanks!
Also, the photo I am trying to retrieve is a .jpg, not sure if that may be important.
(Here's the rest of the code if it is needed)
import UIKit
class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var activities = [AnyObject]()
var images = [UIImage]()
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//tableView.contentInset = UIEdgeInsetsMake(2, 0, 0, 0)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return activities.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "activity", for: indexPath) as! CustomCell
let post = activities[indexPath.row]
let image = images[indexPath.row]
let username = post["username"] as? String
let text = post["text"] as? String
cell.titleLbl.text = text
cell.userLbl.text = username
cell.activityImage.image! = image
//cell.dateLbl.text = activities[indexPath.row]
//cell.activityImage.image = images[indexPath.row]
return cell
}
override func viewWillAppear(_ animated: Bool) {
loadActivities()
}
func loadActivities() {
let id = user!["id"] as! String
let url = URL(string: "https://cgi.soic.indiana.edu/~team7/posts.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let body = "id=\(id)&text=&uuid="
request.httpBody = body.data(using: String.Encoding.utf8)
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
if error == nil {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
// clean up
self.activities.removeAll(keepingCapacity: false)
self.images.removeAll(keepingCapacity: false)
self.tableView.reloadData()
guard let parseJSON = json else {
print("Error while parsing")
return
}
guard let posts = parseJSON["posts"] as? [AnyObject] else {
print("Error while parseJSONing")
return
}
self.activities = posts
for i in 0 ..< self.activities.count {
let path = self.activities[i]["path"] as? String
if !path!.isEmpty {
let url = URL(string: path!)!
let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!
self.images.append(image)
} else {
let image = UIImage()
self.images.append(image)
}
}
self.tableView.reloadData()
} catch {
}
} else {
}
})
}.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension NSMutableData {
func appendString(_ string : String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
append(data!)
}
}
Why are you doing all of this ? Get the URLs of the images from your server and then load them asynchronously in cellForRowAtIndexPath using SDWebImage. It is a library you can find it here. https://github.com/rs/SDWebImage. This way you won't need to store your images in an array and it will be faster to load.
Or you can also implement your own async loading of images.
you could try something like this to avoid runtime errors:
if let actualPath = path, !actualPath.isEmpty, let url = URL(string: actualPath) {
if let imageData = try? Data(contentsOf: url) {
if let image = UIImage(data: imageData) {
self.images.append(image)
}
}
}
instead of this
if!path!.isEmpty {
let url = URL(string: path!)!
let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!
self.images.append(image)
}

UIAlertController cannot be display and keeps getting error (Swift, Xcode)

I would like to display a UIAlertController after getting a jSON response from my php server, so upon checking there is a return id from the response, in the if else statement, i wrote a code to display a UIAlertController but i could not get it to work.
Here is a snippet of my error
Assertion failure in -[UIKeyboardTaskQueue waitUntilAllTasksAreFinished]
My IBAction button codes
#IBAction func btnRegister(sender: AnyObject) {
let parameters = ["name": tfName.text! , "contact": tfContact.text! ,"email": tfEmail.text!] as Dictionary<String, String>
let request = NSMutableURLRequest(URL: NSURL(string:"http://192.168.1.8/safeproject/registerprofile.php")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
//Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])
let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
let successAlert = UIAlertController(title: "Registration Status", message:"Register Success", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
let failAlert = UIAlertController(title: "Registration Status", message:"Register Fail", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
// Present the controller
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("Response: \(json)")
let id = json["id"]!
if(id.isEqual(""))
{
self.presentViewController(failAlert, animated: true){}
print("User register fail");
}
else
{
self.presentViewController(successAlert, animated: true){}
print("User register success");
}
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
}
task.resume()
}
When you are trying to display the alert controller you are working on a separate thread so you need to switch back before displaying it.
if(id.isEqual("")){
NSOperationQueue.mainQueue().addOperationWithBlock {
self.presentViewController(failAlert, animated: true){}
}
}...

how to upload image in swift 2 to php server

I am trying to upload photos to my database in my server from my iPhone app. the language I am using is swift 2. please help me. I am attaching my code to upload the other details to the JSON link and I want to add image also to my link. please help me
import UIKit
class MealViewController: UIViewController, UITextFieldDelegate,
UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var photoImageView: UIImageView!
#IBOutlet weak var ratingControl: RatingControl!
#IBOutlet weak var usernameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Handle the text field’s user input through delegate callbacks.
nameTextField.delegate = self
let attributes = [
NSForegroundColorAttributeName: UIColor.blueColor(),
NSFontAttributeName: UIFont(name: "Avenir", size: 2)!
]
self.navigationController?.navigationBar.titleTextAttributes = attributes
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
}
// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// The info dictionary contains multiple representations of the image, and this uses the original.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
print("my image ", photoImageView)
// Dismiss the picker.
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: Actions
#IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
// Hide the keyboard.
//nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .PhotoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int
if (isLoggedIn != 1) {
self.performSegueWithIdentifier("goto_login", sender: self)
} else {
self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String
}
}
#IBAction func ratingSubmitButton(sender: UIButton) {
print(ratingControl.rating)
print(self.usernameLabel.text!)
let name:NSString = self.usernameLabel.text!
let value = ratingControl.rating
let imageData = UIImagePNGRepresentation(photoImageView.image!)
do {
let post:NSString = "name=\(name)&value=\(value)"
NSLog("PostData: %#",post);
let url:NSURL = NSURL(string:"http://kiran.com/insert.php")!
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData?
do {
urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
} catch let error as NSError {
reponseError = error
urlData = nil
}
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %#", responseData);
//var error: NSError?
let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
//[jsonData[#"success"] integerValue];
NSLog("Success: %ld", success);
if(success == 1)
{
NSLog("Login SUCCESS");
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
prefs.setObject(name, forKey: "USERNAME")
prefs.setInteger(1, forKey: "ISLOGGEDIN")
prefs.synchronize()
self.performSegueWithIdentifier("goto_rating", sender: self)
} else {
var error_msg:NSString
if jsonData["error_message"] as? NSString != nil {
error_msg = jsonData["error_message"] as! NSString
} else {
error_msg = "Unknown Error"
}
let alertView:UIAlertView = UIAlertView()
alertView.title = "Rating Failed"
alertView.message = error_msg as String
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} else {
}
} else {
}
} catch {
let alertView:UIAlertView = UIAlertView()
alertView.title = "Rating Success!"
alertView.message = "Thank You"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
#IBAction func logOutButton(sender: UIButton) {
let appDomain = NSBundle.mainBundle().bundleIdentifier
NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain!)
self.performSegueWithIdentifier("goto_login", sender: self)
}
`

Categories