Xcode func used in another View Controller - mysql

I have this func in a Swift file, and it returns the value of the data in the database and prints it out in the counsel.
I want to use the value in the other View Controller but I can't get this to work, so I hope somebody can help me.
It is the nameUser, statusUser and pointUser I like to use in other View Controller.
import Foundation
import UIKit
var code = "100"
var getStatusUSer = ""
class getJSON: NSObject, URLSessionDataDelegate
{
//properties
var data : NSMutableData = NSMutableData()
func downloadItems()
{
let url = NSMutableURLRequest(url: NSURL(string: "http://www.hholm.dk/time_app/qrcode4.php")! as URL)
url.httpMethod = "POST"
let postString = "username=\(code)"
url.httpBody = postString.data(using: String.Encoding.utf8)
print(url.httpBody = postString.data(using: String.Encoding.utf8))
var session: URLSession!
let configuration = URLSessionConfiguration.default
session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTask(with: url as URLRequest)
task.resume()
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
{
self.data.append(data as Data);
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
{
if error != nil
{
print("Not Found", error)
}
else
{
print("Ok")
self.parseJSON()
}
}
func parseJSON()
{
var jsonResult: NSArray = NSArray()
do
{
jsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
print("jsonResult.count",jsonResult.count)
}
catch let error as NSError
{
print("jsonResult: ", error)
}
var jsonElement: NSDictionary = NSDictionary()
var contador = 0
for i in (0..<jsonResult.count)
{
jsonElement = jsonResult[i] as! NSDictionary
if let nameUser = jsonElement["name"] as? String,
let pointUser = jsonElement["point"] as? String,
let statusUser = jsonElement["status"] as? String
{
getStatusUSer = statusUser
print("Name: ", nameUser)
print("Status: ", statusUser)
print("Point: ", pointUser)
}
}
}
}
Hi Woof this is what i have in my viewcontroler:
import UIKit
class inputcodeViewController: UIViewController {
#IBOutlet weak var input: UITextField!
#IBAction func but(_ sender: Any) {
downloadItems()
}
func downloadItems(){
let getJson = GetJSON()
//setting the delegate
getJson.delegate = self
//starting download
getJson.downloadItems()
}
}
extension inputcodeViewController: GetJSONDelegate {
func didReceiveValues(name: String, status: String, point: String){
//now you can use values in your view controller
}
}
how can i print the values

You can use protocol to return those values:
import Foundation
import UIKit
var code = "100"
var getStatusUSer = ""
//define the protocol
protocol GetJSONDelegate {
func didReceiveValues(name: String, status: String, point: String)
}
//I've changed the first char of the class name to uppercase
class GetJSON: NSObject, URLSessionDataDelegate{
//properties
var data : NSMutableData = NSMutableData()
//delegate
var delegate: GetJSONDelegate?
func downloadItems(){
let url = NSMutableURLRequest(url: NSURL(string: "http://www.hholm.dk/time_app/qrcode4.php")! as URL)
url.httpMethod = "POST"
let postString = "username=\(code)"
url.httpBody = postString.data(using: String.Encoding.utf8)
print(url.httpBody = postString.data(using: String.Encoding.utf8))
var session: URLSession!
let configuration = URLSessionConfiguration.default
session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTask(with: url as URLRequest)
task.resume()
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
{
self.data.append(data as Data);
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
{
if error != nil
{
print("Not Found", error)
}
else
{
print("Ok")
self.parseJSON()
}
}
func parseJSON()
{
var jsonResult: NSArray = NSArray()
do
{
jsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
print("jsonResult.count",jsonResult.count)
}
catch let error as NSError
{
print("jsonResult: ", error)
}
var jsonElement: NSDictionary = NSDictionary()
var contador = 0
for i in (0..<jsonResult.count)
{
jsonElement = jsonResult[i] as! NSDictionary
if let nameUser = jsonElement["name"] as? String,
let pointUser = jsonElement["point"] as? String,
let statusUser = jsonElement["status"] as? String
{
getStatusUSer = statusUser
print("Name: ", nameUser)
print("Status: ", statusUser)
print("Point: ", pointUser)
//here we will return received data to the delegate
self.delegate?.didReceiveValues(name: nameUser, status: statusUser, point: pointUser)
}
}
}
}
Now we need to set your controller as a delegate for that protocol:
//this is an example, you need to add the methods described in your controller where you want to use those values
class YourViewController: UIViewController{
// the method that is called by you to get values
func downloadItems(){
let getJson = GetJSON()
//setting the delegate
getJson.delegate = self
//starting download
getJson.downloadItems()
}
}
//defining protocol methods in the extension of the view controller
extension YourViewController: GetJSONDelegate {
func didReceiveValues(name: String, status: String, point: String){
//now you can use values in your view controller
}
}

Related

how to create mapkit annotations by using data json data from server?

I read from my server and print it out in my xcode project. But when I tried to represent the json code to show mapkit annotations according to latitude and longitude from the server it would not work.
Here is my structure:
struct User {
var locaitonid: String
var latitude: Double
var longitude: Double
var cityName: String
init(_ dictionary: [String: Any]) {
self.locaitonid = dictionary["location_id"] as? String ?? ""
self.latitude = dictionary["latitude"] as? Double ?? 0.0
self.longitude = dictionary["longitude"] as? Double ?? 0.0
self.cityName = dictionary["city_name"] as? String ?? ""
}
Here is my viewController code:
class ViewController: UIViewController {
var model = [User]()
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "http://web server link ") else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: [])
// print(jsonResponse) //Response result
guard let jsonArray = jsonResponse as? [[String: Any]] else {
return
}
for dic in jsonArray{
let annotation = MKPointAnnotation()
annotation.title = (dic["location_id"] as! String)
annotation.subtitle = (dic["city_name"]as! String)
annotation.coordinate = CLLocationCoordinate2D(latitude: dic["latitude"]as!Double, longitude: dic["longitude"]as!Double)
self.mapView.addAnnotations([annotation])
self.mapView.showAnnotations([annotation], animated: true)
}
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
Try the following code
class ViewController: UIViewController {
var model = [User]()
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "http://web server link ") else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: [])
// print(jsonResponse) //Response result
guard let jsonArray = jsonResponse as? [[String: Any]] else {
return
}
for dic in jsonArray{
let annotation = MKPointAnnotation()
annotation.title = (dic["location_id"] as! String)
annotation.subtitle = (dic["city_name"]as! String)
annotation.coordinate = CLLocationCoordinate2D(latitude: dic["latitude"]as!Double, longitude: dic["longitude"]as!Double)
DispatchQueue.main.async {
self.mapView.addAnnotations([annotation])
self.mapView.showAnnotations([annotation], animated: true)
}
}
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}

json data not getting loaded into UITextView in swift

class ViewController:ViewController,UITextViewDelegate{
#IBOutlet weak var newTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
newTextView.delegate = self
dataFun()
}
func dataFun()
{
let url : String = "http:xyz/abc"
let request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"
print("Start")
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request) { (data, response, error) -> Void in
do {
let jsonResult: NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary
print("In method\(jsonResult)")
// let data = jsonResult["description"]
// print(data!)
if (jsonResult != nil)
{
// process jsonResult
print("Data added")
let test:String = jsonResult["description"] as! String
print(test)
self.newTextView.text = test
} else {
print("No Data")
// couldn't load JSON, look at error
}
}
catch {
print("Error Occured")
}
}
.resume()
}
In my app I am going to call services from API
I can see my json data in console.
that data is not show in textviewController
it shows fatal error:
unexpectedly found nil while unwrapping an Optional value
and then crash the app
Make sure #IBOutlet weak var newTextView: UITextView! is set up correctly.
Make sure let test:String = jsonResult["description"] as! String doesn't crash. JSON has field description and it's a string.

Error parsing JSON in Swift2

Hello I am having an error when parsing some JSON in Swift, my error is:
'Invalid conversion from throwing function of type '(_, _, _) throws -> Void' to non-throwing function type '(NSData?, NSURLResponse?, NSError?) -> Void'
I think this is something to do with catching an error somewhere but I cannot figure out where this would go could anyone help me please? Here is my source code:
import UIKit
import CoreData
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
override func viewDidLoad() {
super.viewDidLoad()
var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context: NSManagedObjectContext = appDel.managedObjectContext
let url = NSURL(string: "https://www.googleapis.com/blogger/v3/blogs/10861780/posts?key=AIzaSyBwmI4AzMnBmr7oSVeL0EHdzMjXV1aATnQ")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error)
} else {
//print(NSString(data: data!, encoding: NSUTF8StringEncoding))
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as! NSDictionary
if jsonResult.count > 0 {
if let items = jsonResult["items"] as? NSArray {
for items in items {
print(items)
if let title = items["title"] as? String {
if let content = items["content"] as? String {
var newPost: NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName("Posts", inManagedObjectContext: context)
newPost.setValue(title, forKey: "title")
newPost.setValue(content, forKey: "content")
do {
try context.save()
}
}
}
}
}
}
} catch let error as NSError {
print(error)
}
var request = NSFetchRequest(entityName: "Posts")
request.returnsObjectsAsFaults = false
var results = try context.executeFetchRequest(request)
self.tableView.reloadData()
}
})
task.resume()
}
Thanks!
It looks like you haven't taken care of all the throwing functions using do-try-catch method.
According to the Swift 3 Documentation at https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html
In your case, you seem to have forgotten to take care of the error thrown at var- results. Also, you haven't handled the throwing function session.dataTaskWithURL with a do-try-catch method.
You should not be getting this error if you modify your code as following:
override func viewDidLoad() {
super.viewDidLoad()
var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context: NSManagedObjectContext = appDel.managedObjectContext
let url = NSURL(string: "https://www.googleapis.com/blogger/v3/blogs/10861780/posts?key=AIzaSyBwmI4AzMnBmr7oSVeL0EHdzMjXV1aATnQ")
let session = NSURLSession.sharedSession()
do {
let task = try session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error)
} else {
//print(NSString(data: data!, encoding: NSUTF8StringEncoding))
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as! NSDictionary
if jsonResult.count > 0 {
if let items = jsonResult["items"] as? NSArray {
for items in items {
print(items)
if let title = items["title"] as? String {
if let content = items["content"] as? String {
var newPost: NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName("Posts", inManagedObjectContext: context)
newPost.setValue(title, forKey: "title")
newPost.setValue(content, forKey: "content")
do {
try context.save()
} catch let error1 as NSError { // this is for context.save
print(error1)
}
}
}
}
}
}
}
var request = NSFetchRequest(entityName: "Posts")
request.returnsObjectsAsFaults = false
do{
var results = try context.executeFetchRequest(request)
} catch let error2 as NSError { // this is for context.executeFetchRequest
print(error2)
}
self.tableView.reloadData()
}
})
task.resume()
} catch let error3 as NSError { // this is for session.dataTaskWithURL
print(error3)
}
}
Hope this helps ! Cheers !

How do I use json instead of plist to populate TableView

I have a working App which takes data from a pList on a remote server. However, I now want to use json instead of plist and am struggling with understanding how to do this! Any help much appreciated and any examples awesome.
Some selected code - first download of plist and second populating the TableView using the downloaded plist. Note: I have not included ALL the code.
#IBAction func startDownload(sender: AnyObject) {
progressView.hidden = false
let url = NSURL(string: "http://ftp.iphoneData#dittodata.host-ed.me/Annotations/myAnnotationsKalkan.plist")!
downloadTask = backgroundSession.downloadTaskWithURL(url)
downloadTask.resume()
}
func showFileWithPath(path: String){
let isFileFound:Bool? = NSFileManager.defaultManager().fileExistsAtPath(path)
if isFileFound == true{
let viewer = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: path))
viewer.delegate = self
viewer.presentPreviewAnimated(true)
// print("file is found")
}
}
#IBOutlet var progressView: UIProgressView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 1
func URLSession(session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL){
let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentDirectoryPath:String = path[0]
let fileManager = NSFileManager()
let destinationURLForFile = NSURL(fileURLWithPath: documentDirectoryPath.stringByAppendingString("/myAnnotationsKalkan.plist.plist"))
if fileManager.fileExistsAtPath(destinationURLForFile.path!){
showFileWithPath(destinationURLForFile.path!)
}
else{
do {
try fileManager.moveItemAtURL(location, toURL: destinationURLForFile)
// show file
showFileWithPath(destinationURLForFile.path!)
}catch{
print("An error occurred while moving file to destination url")
}
}
}
// 2
func URLSession(session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64){
progressView.setProgress(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite), animated: true)
}
func URLSession(session: NSURLSession,
task: NSURLSessionTask,
didCompleteWithError error: NSError?){
downloadTask = nil
progressView.setProgress(0.0, animated: true)
if (error != nil) {
print(error?.description)
}else{
// print("The task finished transferring data successfully")
progressView.hidden = true
}
}
// TableViewController.swift
/ museumTemplate
//
import UIKit
class MyTableViewController: UITableViewController {
var titleData = [String]()
var subTitleData = [String]()
var stateData = [String]()
var codeData = [String]()
var infoData = [String]()
var openData = [String]()
var phoneData = [String]()
var emailData = [String]()
var webData = [String]()
var latData = [Double]()
var lonData = [Double]()
var titleToPass = [String]()
var thisState = [String]()
var stateOrAlpha = ""
var titleText = ""
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = titleText
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let sourcePath = documentsPath.stringByAppendingPathComponent("myAnnotationsKalkan.plist.plist")
if let content = NSArray(contentsOfFile: sourcePath as String){
let descriptor = NSSortDescriptor(key: stateOrAlpha, ascending: true)
let myMuseum = content.sortedArrayUsingDescriptors([descriptor])
for item in myMuseum{
titleData.append(item.objectForKey("title") as! String)
subTitleData.append(item.objectForKey("subtitle") as! String)
infoData.append(item.objectForKey("info") as! String)
phoneData.append(item.objectForKey("phone") as! String)
webData.append(item.objectForKey("web") as! String)
emailData.append(item.objectForKey("email") as! String)
latData.append(item.objectForKey("latitude") as! Double)
lonData.append(item.objectForKey("longitude") as! Double)
}
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return titleData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) as UITableViewCell
// Configure the cell..title and subTitle.
cell.textLabel!.text = titleData[indexPath.row]
return cell
}
i use Alamofire wich is more easier and safe to do Web requests, but here is a code without it:
let urlPath = "YourUrlRequest"
let session = NSURLSession.sharedSession()
let url = NSURL(string: urlPath)!
session.dataTaskWithURL(url) {( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if let responseData = data {
do {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as! NSArray
for dataDict : AnyObject in jsonObject {
let idj: String = dataDict.objectForKey("id") as!String
let namej: String = dataDict.objectForKey("name") as! String
let indicativej: String = dataDict.objectForKey("indicative") as! String
let flagj: String = dataDict.objectForKey("flag") as! String
saveCountryFromWeb(idj, name: namej, indicative: indicativej, flag: flagj)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
}.resume()
Hope the helps, tell me in case you want a sample with alamofire which i recommend ;)
func retrieveBarcodeData(){
let databaseref = FIRDatabase.database().reference()
databaseref.child("barcodes").queryOrderedByKey().observeEventType(.ChildAdded, withBlock: {
snapshot in
let codig = snapshot.value!["codigo"] as! String
let desc = snapshot.value!["designacao"] as! String
let Url = snapshot.value!["ImageURL"] as! String
barcodes.insert(BarCodeStruct(code: codig, description: desc, ImageURL: Url),atIndex: 0)
self.tableView.reloadData()
})
}
Don't forget to configure your database in firebase, and install firebase with cocoapods and put FIRApp.configure() in your appDelegate didFinishLaunchingWithOptions
I tried this code for downloading a simple json file from a server and it seems to work:
override func viewDidLoad() {
super.viewDidLoad()
let requestURL: NSURL = NSURL(string: "http://ftp.iphoneData#dittodata.host-ed.me/Annotations/testData4.json")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("File downloaded.")
// print(testData4.json)
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let users = json["users"] as? [[String: AnyObject]] {
for user in users {
if let name = user["name"] as? String {
if let subtitle = user["subtitle"] as? String {
print(name,subtitle)
}
}
}
}
}catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}

Get value from JSON file in Swift

I have a JSON file which i converted to a NSDictionary object. My question is how do i get one single value out from this object? I make a httppost to my webside and then i get an JSON array back with to values "success" and "userId" i want to check on the success if it is true or false.
import UIKit
class ViewController2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func HttpBtn(sender: AnyObject) {
PostToServer()
HttpPost()
}
func PostToServer()
{
println("Button Presed")
}
func HttpPost()
{
var postString = "email=joakim#and.dk&password=123456"
//Declare URL
var url: NSURL! = NSURL(string: "http://95.85.53.176/nhi/api/app/login")
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
//Declare which HTTPMethod
request.HTTPMethod = "POST"
//POST data
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if error != nil
{
println("error=\(error)")
return
}
println("response =\(response)")
var responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString =\(responseString)")
var error: NSError?
var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &error) as? NSDictionary
println(myJSON)
}
task.resume()
}
}
output
responseString =Optional({"success":true,"userId":"62"})
Optional({
success = 1;
userId = 62;
})
You can access using its key value like
var success = myJSON["success"]!.intValue
var userId = myJSON["userId"]!.intValue
if(success == 1) //if true
{
//Do something
}
Same with userId