Pull To Refresh Not Refreshing JSON Data - php

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

Related

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)
}

How to fetch JSON data into UIPickerView in Swift 3.0 ?

My question is, how to fetch data from PHP into UIPickerView in Swift 3.0 ?
Currently, I have these code for UIPickerView to create dropdown list. Right now, I can only display the dropdown list value based on variable declare inside xcode var department = ["ICTD","FAD","PSD"]
dropdown.swift
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
#IBOutlet var departmentLbl: UITextField!
#IBOutlet var dropdownLbl: UIPickerView!
#IBOutlet var outputLbl: UILabel!
#IBOutlet var user_idLbl: UILabel!
var department = ["ICTD","FAD","PSD"]
var user_id: String!
override func viewDidLoad() {
super.viewDidLoad()
user_id = "ID001" // these value that need to be past to PHP
let url = URL(string: "http://localhost/getdepartment.php")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
let LoginDataToPost = "user_id=\(user_id!)"
request.httpBody = LoginDataToPost.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if error != nil { return }
else {
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String] {
DispatchQueue.main.async {
let display = Int(json["display"]!)
let realname = json["real_name"]
let department = json["dept"]
if(display == 1) {
// dropdown list value display here
return
}
else { return }
}
}
else { }
}
catch {}
}
})
task.resume()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
var countrows : Int = department.count
if pickerView == dropdownLbl {
countrows = self.department.count
}
return countrows
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == dropdownLbl {
let titleRow = department[row]
return titleRow
}
return ""
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == dropdownLbl {
self.departmentLbl.text = self.department[row]
self.dropdownLbl.isHidden = true
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if (textField == self.departmentLbl) {
self.dropdownLbl.isHidden = false
}
}
}
And I have these PHP code that gives an output of
real name and department
based on user_id value from x code
getdepartment.php
<?php
$connect = mysqli_connect("","","","");
global $connect;
if (isset($_POST['user_id'])) {
$user_id = $_POST['user_id'];
$sql = "SELECT * FROM table WHERE user_id ='$user_id'";
$result = mysqli_query($connect,$sql);
if($result && mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_array($result)) {
$real_namedb = $row['real_name'];
$dept_db = $row['dept'];
$output = array('real_name' => $real_namedb, 'dept' => $dept_db);
echo json_encode($output);
}
mysqli_free_result($result);
}
else { }
}
?>
These PHP gives an output of JSON data as below:
{"display":"1","real_name":"NAME TEST 1","dept":"ICTD"}
{"display":"1","real_name":"NAME TEST 2","dept":"ICTD"}
Appreciate if someone can help.
Thanks.
I believe you are supposed to create the dropdownlist based on values you received from server. Based on the code you've given in the question, I observed that you were not adding department names you got from the server to your array.
You can make following changes and observe:
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String]
{
DispatchQueue.main.async
{
let display = Int(json["display"]!)
let realname = json["real_name"]
let departmentName = json["dept"]
if(display == 1) {
// dropdown list value display here
self.department.append(departmentName)
self.dropdownLbl.reloadAllComponents() // this is reference to your pickerView. Make it global and use it
return
}else { return }
}
}
Please let me know if it resolves the problem or not...

When calling PHP service from Swift for iOS 9, results don't display

I'm new to Swift and trying to set up an iOS app. At the start of the app I'm dropping a pin on the map and sending the location to my php web service. Then after the next 10 iterations through the map movement, another pin is to be dropped and the location gets sent to the service. Looking at the database everything is getting to the service and is getting loaded to the tables. But, the first time calling the service is the only time that the response data can be retrieved.
Here's the view controller:
//
// ViewController.swift
// Tracker
//
// Created by Kendall Crouch on 2/6/16.
// Copyright © 2016 KLC Computing. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
var places = [Dictionary<String, String>()]
var hasStarted: Bool = false
var locationCount = 0
var routeId: NSInteger = -1
var lastStep: NSInteger = -1
var markerId: Int = -1
var manager:CLLocationManager!
#IBOutlet weak var mapView: MKMapView!
#IBOutlet weak var lblLatitude: UILabel!
#IBOutlet weak var lblLongitude: UILabel!
#IBOutlet weak var btnStartControl: UIBarButtonItem!
#IBOutlet weak var btnPauseControl: UIBarButtonItem!
#IBOutlet weak var btnStopControl: UIBarButtonItem!
#IBAction func btnStart(sender: AnyObject) {
btnStartControl.enabled = false
btnPauseControl.enabled = true
btnStopControl.enabled = true
manager.startUpdatingLocation()
}
#IBAction func btnPause(sender: AnyObject) {
manager.stopUpdatingLocation()
self.btnStartControl.enabled = true
self.btnPauseControl.enabled = false
hasStarted = false
}
#IBAction func btnStop(sender: AnyObject) {
manager.stopUpdatingLocation()
self.btnStopControl.enabled = false
self.btnStartControl.enabled = true
hasStarted = false
}
override func viewDidLoad() {
super.viewDidLoad()
locationCount = 500
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationCount += 1
let userLocation:CLLocation = locations[0]
let latitude: CLLocationDegrees = userLocation.coordinate.latitude
let longitude: CLLocationDegrees = userLocation.coordinate.longitude
lblLatitude.text = String(userLocation.coordinate.latitude)
lblLongitude.text = String(userLocation.coordinate.longitude)
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
mapView.setRegion(region, animated: false)
let newCoordinate: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let newLocation = CLLocation(latitude: newCoordinate.latitude, longitude: newCoordinate.longitude)
if locationCount > 10 {
hasStarted = false
locationCount = 0
}
if !hasStarted {
hasStarted = true
CLGeocoder().reverseGeocodeLocation(newLocation) { (placemarks, error) -> Void in
var title = "Added on \(NSDate())"
if error != nil {
print(error)
}
else {
if let p = placemarks?[0] {
let formattedAddressLines = p.addressDictionary?["FormattedAddressLines"] as! NSArray
title = formattedAddressLines.componentsJoinedByString(", ")
}
}
let annotation = MKPointAnnotation()
annotation.coordinate = newCoordinate
annotation.title = title
self.mapView.addAnnotation(annotation)
self.places.append(["name":title, "lat":"\(newCoordinate.latitude)", "lon":"\(newCoordinate.longitude)"])
NSUserDefaults.standardUserDefaults().setObject(self.places, forKey: "places")
let url: NSURL = NSURL(string: "http://tracker.klccomputing.com/updateRoute.php")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let bodyData = "routeId=\(self.routeId)&routeName=\(title)&routeDate=\(NSDate())&lastStep=\(self.lastStep)&latitude=\(newLocation.coordinate.latitude)&longitude=\(newLocation.coordinate.longitude)"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
print(data)
if let HTTPResponse = response as? NSHTTPURLResponse {
let statusCode = HTTPResponse.statusCode
if statusCode == 200 {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let jsonData = json {
print("KLCA\(jsonData)")
if let newRouteId: NSInteger = jsonData["routeId"] as? NSInteger {
self.routeId = newRouteId
if let newLastStep: NSInteger = jsonData["lastStep"] as? NSInteger {
self.lastStep = newLastStep
print("KLCB\(self.lastStep)")
}
}
}
}
catch {
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("raw response: \(responseString)")
}
}
}
})
task.resume()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Console information. I let the app run 3 iterations. The first time through the variable if statement to get the information from the variable jsonData worked. The second and third times through, they didn't work:
Optional(<7b22726f 75746549 64223a31 362c226d 61726b65 72496422 3a36312c 226c6173 74537465 70223a31 7d>)
KLCA{
lastStep = 1;
markerId = 61;
routeId = 16;
}
KLCB1
Optional(<7b22726f 75746549 64223a22 3136222c 226d6172 6b657249 64223a36 322c226c 61737453 74657022 3a327d>)
KLCA{
lastStep = 2;
markerId = 62;
routeId = 16;
}
Optional(<7b22726f 75746549 64223a22 3136222c 226d6172 6b657249 64223a36 332c226c 61737453 74657022 3a327d>)
KLCA{
lastStep = 2;
markerId = 63;
routeId = 16;
}

HTTP Post Request check in swift

i have php file to check a value passed from swift ios, i print json data, this is the code:
<?php
$said = $_REQUEST['sa_id'];
if($said == '123456') {
$returnValue = array("said" => "true");
}else{
$returnValue = array("said" => "false");
}
echo json_encode($returnValue);
?>
Also i wrote a swift function to check the returned said value, my code is work success in second click, i want it from first click:
class ViewController: UIViewController {
var saidResult = false;
#IBOutlet var saidField: UITextField!
#IBOutlet var labelField: UILabel!
override func viewDidLoad(){
super.viewDidLoad()
}
#IBAction func checkSAID(sender: UIButton) {
if ( isValidSAID(saidField.text) == false ) {
labelField.text = "SAID is Invalid"
} else {
labelField.text = "Done"
}
}
func isValidSAID(said2Test: String) -> Bool {
let myUrl = NSURL(string: "http://*****.com/said.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
// Compose a query string
let postString = "sa_id=\(said2Test)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
(data, response, error) in
if error != nil {
println("error=\(error)")
return
}
// You can print out response object
println("response = \(response)")
// Print out response body
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
//Let's convert response sent from a server side script to a NSDictionary object:
var err: NSError?
var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSDictionary
if let parseJSON =myJSON {
// Now we can access value of First Name by its key
var saidValue = parseJSON["said"] as? String
println("saidValue: \(saidValue)")
if ((saidValue) == "true" ) {
self.saidResult = true;
}
println("saidResult: \(self.saidResult)");
}
}
task.resume()
println("saidResult: \(self.saidResult)");
if ( self.saidResult == true ){
return true
} else {
return false
}
}
}
As i say, in first click the value of saidResult is false but after that it is take the true value
How i can solve this issue, or is there another way to improve my code?
I think this is probably because the http request is not answered on the first click but is on the second click.
you could try replacing your checkSAID function with this.
#IBAction func checkSAID(sender: UIButton) {
let saidQueue = dispatch_queue_create("saidQueue", DISPATCH_QUEUE_CONCURRENT)
// Do the checking on a background thread.
dispatch_async(saidQueue, {
if ( isValidSAID(saidField.text) == false ) {
// As the UI updates are performed on the main queue, update the label on the main queue.
dispatch_async(dispatch_get_main_queue()) {
labelField.text = "SAID is Invalid"
})
} else {
dispatch_async(dispatch_get_main_queue()) {
labelField.text = "Done"
})
}
})
}
Finally, after 4 days of testing i solved my problem.
I changed isValidSAID function code:
func isValidSAID(said2Test: String) -> Bool {
var status: String = "";
let myUrl = NSURL(string: "http://*****.com/said.php?sa_id=\(said2Test)");
let data = NSData(contentsOfURL: myUrl!)
let json = NSHSONSerialization.JSONObjectWithData(data!, option: nil, error: nil) as! NSDictionary
status = (json["said"] as? String)!
println(status)
return ( status == "true" ) ? true : false
}
and solved my issue.

Categories