How to show data by ID in TableView from JSON - php

I get the data from JSON and also can show it in UITableView, but can I show the data where id is = 1 for example? just like SQL? Thanks for help in advance. Here is my code. I have 2 TableViews, first one holds 3 users and the 2nd one should have that user Information, but when I click on one user it shows all the information from all users.
import UIKit
struct User: Codable {
let firstName: String
let lastName: String
let email: String
let userid: String
enum CodingKeys: String, CodingKey {
case firstName = "first_name"
case lastName = "last_name"
case email = "email"
case userid = "user_id"
}
}
class tableViewCellLabels: UITableViewCell {
#IBOutlet var lbl_firstName: UILabel!
#IBOutlet var lbl_lastName: UILabel!
#IBOutlet var lbl_email: UILabel!
#IBOutlet var lbl_userid: UILabel!
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableview1: UITableView!
#IBOutlet var tableview2: UITableView!
private var dataSource = [User]() {
didSet {
self.tableview1.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableview1.dataSource = self
self.tableview1.delegate = self
let url = URL(string: "https://test.netperformers.de/users")
URLSession.shared.dataTask(with: url!, completionHandler: { [weak self] (data, response, error) in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "An error occurred")
return
}
DispatchQueue.main.async {
self?.dataSource = try! JSONDecoder().decode([User].self, from: data)
}
}).resume()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableview1.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == tableView{
print(dataSource[indexPath.row]) // your clicked user data
}else{
// Second Tableview Click Event here
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for: indexPath) as! tableViewCellLabels
let user = self.dataSource[indexPath.row]
cell.lbl_firstName.text = user.firstName
cell.lbl_lastName.text = user.lastName
cell.lbl_userid.text = user.userid
return cell
}
func tableView1(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == tableView{
print(dataSource[indexPath.row]) // your clicked user data
}else{
// Second Tableview Click Event here
}
}
}

You do not need a 2nd UITableVIew to show a single User, its not the correct purpose of this ui control, instead you can do one of followings:
Show UIAlertController with the user information
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let user = self.dataSource[indexPath.row]
let alertController = UIAlertController(title: user.firstName + " " + user.lastName, message: user.email, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default)
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
Create a UIViewController to have a UI that matches your needs, following is a basic example
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let user = self.dataSource[indexPath.row]
let userVC = UserViewController(user: user)
self.navigationController?.pushViewController(userVC, animated: true)
}
class UserViewController: UIViewController {
private let user: User
init(user: User) {
self.user = user
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
let nameLabel = UILabel()
nameLabel.text = self.user.firstName + " " + self.user.lastName
nameLabel.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(nameLabel)
let emailLabel = UILabel()
emailLabel.text = self.user.email
emailLabel.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(emailLabel)
let safeAreaGuide = self.view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
nameLabel.topAnchor.constraint(equalTo: safeAreaGuide.topAnchor, constant: 16.0),
nameLabel.leadingAnchor.constraint(equalTo: safeAreaGuide.leadingAnchor, constant: 16.0),
nameLabel.trailingAnchor.constraint(equalTo: safeAreaGuide.trailingAnchor, constant: 16.0),
emailLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 8.0),
emailLabel.leadingAnchor.constraint(equalTo: safeAreaGuide.leadingAnchor, constant: 16.0),
emailLabel.trailingAnchor.constraint(equalTo: safeAreaGuide.trailingAnchor, constant: 16.0)
])
}
}

If you just need a specific user you can filter the dataSource like this:
dataSource.first(where: { $0.userid == "1" })

Make use of section Header. So all section headers will list the users. In cell for row for each section you can show the information for that particular user. Also you can manage the height of the row for managing the show hide functionality.
Let me know if this helps.

You can do it with a filter array before reloading the tableview.
private var dataSource = [User]() {
didSet {
dataSource = dataSource.filter({ (item) -> Bool in
return item.userid == "3" // put your filter query here
})
self.tableview.reloadData()
}
}
Click Event
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == YourFirstTable {
print(dataSource[indexPath.row]) // your clicked user data
} else {
// Second Tableview Click Event here
}
}

Related

json parsing swift alamofire

I am fetching data from mysql and php with alamofire data is encoded in json which is fetching fine in response now i want to decode and display in tableview how to parse data and display in tableview i have search many examples but not found my solution how to decode and display data in tableview.
<?php
if($_SERVER['REQUEST_METHOD'] == "GET")
{
$conn = mysqli_connect("localhost","id15123058_root2","Ioscrud/12345","id15123058_imageupload");
$query = mysqli_query($conn,"SELECT * FROM `ioscrud`");
while($fetch = mysqli_fetch_array($query))
{
$temp[] = $fetch;
}
$json['jobs'] = $temp;
$jsonformat = json_encode($json);
echo ($jsonformat);
}
?>
This is my php code
import UIKit
class Product:Decodable
{
var name:String
var email:String
var password:String
init(name:String,email:String,password:String) {
self.name = name
self.email = email
self.password = password
}
}
This is class
import UIKit
import Alamofire
class TableViewController: UITableViewController {
#IBOutlet var tableview: UITableView!
var product = [Product]()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
// override func numberOfSections(in tableView: UITableView) -> Int {
// // #warning Incomplete implementation, return the number of sections
// return product.count
// }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return product.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
let url = "https://jobportal475.000webhostapp.com/IosCrud/viewData.php"
AF.request(url,method: .get).response
{response in
debugPrint(response)
if response.data != nil
{
debugPrint(response)
}
}
cell.nameLabel.text = product[indexPath.row].name
cell.emailLabel.text = product[indexPath.row].email
cell.passwordLabel.text = product[indexPath.row].password
return cell
}
}
There is library for directions you can use it if you want
https://github.com/akexorcist/GoogleDirectionLibrary
Or you can use this
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?
saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );
intent.setClassName("com.google.android.apps.maps",
"com.google.android.maps.MapsActivity");
startActivity(intent)

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!

Creating Annotation in MapKit with information from UITableview while using segue

I am currently working on developing an application that pulls data (Address and location information) from a php web service and displays the data as a string in a tableview cell. My tableview is embedded in a Navigation controller, when a cell is clicked a segue links to a map with several hard-coded pins on the map.
I am interested in creating a segue that links a tableview cell (Address) to a specific pin/annotation in a map as a direct reference to the address.
Additionally, I am interested in creating a custom annotation that displays data (Name, Address, photo etc.) regarding its location.
Ideally I am trying to recreate a simpler version of SpotHero.
Thanks!
Heres Some of my code:
TableController:
class TableController: UITableViewController {
var TableData:Array< String > = Array < String >()
var garagedata :Array<String> = Array < String >()
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url("http://cgi.soic.indiana.edu/~team20/service.php")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BasicCell", for: indexPath)
cell.textLabel?.text = TableData[indexPath.row]
//Wrap text in tableview
cell.textLabel?.numberOfLines=0
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//Automatic sizing of tableviewcells
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Segue to the second view controller
self.performSegue(withIdentifier: "detailSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// get a reference to the second view controller
let mapController = segue.destination as! MapController
// set a variable in the second view controller with the data to pass
mapController.receivedData = "Hello"
}
func get_data_from_url(_ link:String)
{
let url:URL = URL(string: link)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
self.extract_json(data!)
})
task.resume()
}
func extract_json(_ data: Data)
{
let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
}
catch
{
return
}
guard let data_list = json as? NSArray else
{
return
}
if let garages_list = json as? NSArray
{
let locations: NSMutableArray = NSMutableArray()
for i in 0 ..< data_list.count
/*{
print(TableData)
if let garage_obj = garages_list[i] as? NSDictionary
{
if let garage_name = garage_obj["GName"] as? String
{
if let garage_address = garage_obj["Address"] as? String
{
if let garage_code = garage_obj["Count"] as? String
{
if let garage_cap = garage_obj["Capacity"] as? String
{
TableData.append(garage_name + "\n"
+ garage_address + " [" + garage_code + "/" + garage_cap+"]")
garagedata.append(garage_name + "\n"
+ garage_address + " [" + garage_code + "/" + garage_cap+"]")
}
}
}
}
}}*/
{
let location = GarageModel()
if let garage_obj = garages_list[i] as? NSDictionary
{
//the following insures none of the JsonElement values are nil through optional binding
if let name = garage_obj["GName"] as? String,
let address = garage_obj["Address"] as? String,
let latitude = garage_obj["Latitude"] as? String,
let longitude = garage_obj["Longitude"] as? String,
let count = garage_obj["Count"] as? String
{
location.name = name
location.address = address
location.latitude = latitude
location.longitude = longitude
location.count = count
}
locations.add(location)
print(locations)
}
}}
DispatchQueue.main.async(execute: {self.do_table_refresh()})
}
func do_table_refresh()
{
self.tableView.reloadData()
}
}
GarageModel:
class GarageModel: NSObject {
//properties
var name: String?
var address: String?
var latitude: String?
var longitude: String?
var count: String?
var capacity: String?
//empty constructor
override init()
{
}
//construct with #name, #address, #latitude, and #longitude parameters
init(name: String, address: String, latitude: String, longitude: String, count: String, capacity: String) {
self.name = name
self.address = address
self.latitude = latitude
self.longitude = longitude
self.count = count
self.capacity = capacity
}
//prints object's current state
override var description: String {
return "Name: \(name), Address: \(address), Latitude: \(latitude), Longitude: \(longitude), Count: \(count), Capacity: \(capacity)"
}
}
I have hardcoded some pins for aesthetic/testing purposes but I do not have these dynamically appearing.
Map Controller:
class MapController : UIViewController {
#IBOutlet weak var mapView: MKMapView!
var receivedData = ""
override func viewDidLoad() {
super.viewDidLoad()
print(receivedData)
let latitude: CLLocationDegrees = 39.173294
let longitude: CLLocationDegrees = -86.520244
let latitude2: CLLocationDegrees = 39.163589
let longitude2: CLLocationDegrees = -86.526266
let latitude3: CLLocationDegrees = 39.167250
let longitude3: CLLocationDegrees = -86.515059
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta)
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let location2 = CLLocationCoordinate2D(latitude: latitude2, longitude: longitude2)
let location3 = CLLocationCoordinate2D(latitude: latitude3, longitude: longitude3)
let region = MKCoordinateRegion(center: location, span: span)
mapView.setRegion(region, animated: true)
let garage1 = MKPointAnnotation()
garage1.title = "Fee Lane Parking Garage"
garage1.subtitle = "Count XX/150 \n 11th and Fee"
garage1.coordinate = location
mapView.addAnnotation(garage1)
let garage2 = MKPointAnnotation()
garage2.title = "Henderson Parking Garage"
garage2.subtitle = "Count XX/150 Fess and Atwater"
garage2.coordinate = location2
mapView.addAnnotation(garage2)
let garage3 = MKPointAnnotation()
garage3.title = "Jordan Parking Garage"
garage3.subtitle = "Count XX/150 North Jordan Street"
garage3.coordinate = location3
mapView.addAnnotation(garage3)
}
}

Pull To Refresh Not Refreshing JSON Data

I been trying to implement a Pull to Refresh to my tableview to refresh JSON Data from server. On what I have tried on the debug Area screen it shows me the data reloads but the Cell labels and images doesn't refresh when I make changes on the PHP file on server .... I'M USING THE CODE BELOW:
import UIKit
class JSONData: UITableViewController {
var newsList = [News]()
override func viewDidLoad() {
super.viewDidLoad()
self.loadJSONDATA()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return newsList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! NewsStrings
let s = newsList[indexPath.row] as News
cell.labellName.text = s.newsName
cell.labelDesc.text = s.newsDesc
cell.labelDate.text = s.newsDate
cell.imgvImage.image = UIImage(named: "BgIcon.jpg")
if let img = UIImage(data: s.newsImage)
{
cell.imgvImage.image = img
}else
{
self.loadImages(s, indexPath: indexPath)
}
return cell
}
///////////////// JSON DATA ////////////////////////
func loadJSONDATA()
{
let urlString = "http://example.com/folder/JSON.php"
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config, delegate:nil, delegateQueue: nil)
if let url = NSURL(string: urlString)
{
let request = NSURLRequest(URL: url)
let taskData = session.dataTaskWithRequest(request, completionHandler: {
(data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if (data != nil)
{
var parseError:NSError?
let parsedNews = (try! NSJSONSerialization.JSONObjectWithData(data!, options: [])) as! NSDictionary
//print("JSON Data \n \(parsedNews)")
if let news:AnyObject = parsedNews["News"]
{
self.parseJSON(news)
}
} else
{
}
})
taskData.resume()
}
}
/////////// LODING JSON DATA //////////////
func parseJSON(jsonData:AnyObject)
{
if let newsData = jsonData as? [[NSObject:AnyObject]]
{
var news:News
for s in newsData {
news = News()
if let sId:AnyObject = s["NewsID"]
{
if let NewsID = sId as? String
{
print("News id = \(NewsID)")
}
}
if let sn:AnyObject = s["newsName"]
{
if let newsName = sn as? String
{
news.newsName = newsName
//println("Store id = \(storeName)")
}
}
if let sn:AnyObject = s["newsDate"]
{
if let newsDate = sn as? String
{
news.newsDate = newsDate
//println("Store id = \(storeName)")
}
}
if let sn:AnyObject = s["newsIcon"]
{
if let newsIcon = sn as? String
{
news.newsImageName = newsIcon
//println("News Icon = \(newsIcon)")
}
}
if let sn:AnyObject = s["newsDesc"]
{
if let newsIcon = sn as? String
{
news.newsDesc = newsIcon
}
}
newsList += [news]
}
NSOperationQueue.mainQueue().addOperationWithBlock(){
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.tableView.reloadData()
}
}
}
/////////// LODING IMAGES FROM JSON DATA //////////////
func loadImages(news:News, indexPath:NSIndexPath)
{
let urlString = news.newsImageName
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config, delegate:nil, delegateQueue: nil)
if let url = NSURL(string: urlString)
{
let request = NSURLRequest(URL: url)
let taskData = session.dataTaskWithRequest(request, completionHandler: {
(data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if (data != nil)
{
news.newsImage = data!
let image = UIImage(data: data!)
dispatch_async(dispatch_get_main_queue(),{
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? NewsStrings {
cell.imgvImage.image = image
}
})
} else
{
}
})
taskData.resume()
}
}
}
You can add pull to refresh within your table view like below code,
var refreshControl = UIRefreshControl()
In view did load,
self.refreshControl.addTarget(self, action: Selector("loadJSONDATA"), forControlEvents: UIControlEvents.ValueChanged)
self.addSubview(self.refreshControl) // OR self.myTable?.addSubview(self.refreshControl)
Then add this line after self.parseJSON(news)
self.refreshControl.endRefreshing()
This will be help full to you. :)
I got something to make it work, this is what I have on my viewDidLoad:
self.refreshControl?.addTarget(self, action: #selector(NewsList.handleRefresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
The Function for the handleRefresh:
func handleRefresh(refreshControl: UIRefreshControl) {
newsList.removeAll() //<-This clear the whole tableview(labels, images,ect...)making table view blank
if self.refreshControl!.refreshing
{
self.loadRecords() //<-Reloads All data & labels
self.refreshControl!.endRefreshing()
}
}
The only thing is that the app crashes after doing the "Pull to refresh" multiples

How can I tell when data has been received with NSURLConnection?

I'm working on a Swift application that uses a PHP web service to query a database. One issue - I have no idea how to tell when data has been received in the model class, so I can't update the view! How can I tell if the connection has finished, then update said view? For this purpose, I've created a dummy label called text. Thanks for the help in advance, and happy holidays!
User.swift
import Foundation
class User: NSObject {
var firstName: String?
var lastName: String?
var username: String
var password: String
var email: String?
var recievedJSON: NSMutableData = NSMutableData()
var userData: [[String: String]]!
var verified: Bool = false
required init(username: String, password: String) {
self.username = username
self.password = password
}
init(firstName: String, lastName: String, username: String, password: String, email: String) {
self.firstName = firstName
self.lastName = lastName
self.username = username
self.password = password
self.email = email
}
func attemptRegister() {
var variables: [String] = ["firstname=" + self.firstName! + "&"]
variables.append("lastname=" + self.lastName! + "&")
variables.append("username=" + self.username + "&")
variables.append("password=" + self.password + "&")
variables.append("email=" + self.email!)
request("https://codekaufman.com/register.php", variables: variables)
}
func attemptSignIn() {
var variables: [String] = ["username=" + self.username + "&"]
variables.append("password=" + self.password)
request("https://codekaufman.com/login.php", variables: variables)
println("Attempting sign-in...")
}
private func request(urlPath: String, variables: [String]?) {
var url: NSURL = NSURL(string: urlPath)!
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
if(variables != nil) {
request.HTTPMethod = "POST"
var bodyData: NSString = ""
for item in variables! {
bodyData = bodyData + NSString(string: item)
}
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
}
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
println("Connection started.")
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.recievedJSON.appendData(data)
println("Possible data recieved.")
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
userData = parseJSON(recievedJSON)
if(userData != nil) {
println("Data recieved:")
println(userData[0])
self.firstName = userData[0]["first_name"]
self.lastName = userData[0]["last_name"]
} else {
println("No data recieved.")
}
}
func parseJSON(inputData: NSData) -> [[String: String]]? {
var error: NSError?
var userData: [[String: String]]!
userData = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? [[String: String]]
#if DEBUG
if (userData != nil) {
println("NSData had data, printing and returning.")
println(userData)
} else {
println("NSData empty, returning nil.")
}
#endif
return userData
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBAction func prepareForUnwind(seque: UIStoryboardSegue) {
}
#IBOutlet weak var username: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var text: UILabel!
#IBAction func signin(sender: AnyObject) {
if(username.text == "" || password.text == "") {
var alert = UIAlertController(title: "Error", message: "Invalid Credentials", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
var attempt: User = User(username: username.text, password: password.text)
attempt.attemptSignIn()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Edit: Based on previous comments/answers, I feel I should clarify. Data is being received. But it takes a few seconds, so how can I signify to the view controller that the data has been received, and the process is finished?
You can add a notification in the view controller with:
func addObserverForName(_ name: String?, object obj: AnyObject?, queue queue: NSOperationQueue?, usingBlock block: (NSNotification!) -> Void) -> NSObjectProtocol
Be sure to remove it in deinit:
func removeObserver(_ notificationObserver: AnyObject)
Send the notification from connectionDidFinishLoading using:
func postNotificationName(_ notificationName: String, object notificationSender: AnyObject?, userInfo userInfo: [NSObject : AnyObject]?)

Categories