Swift Login app - swift

I'm trying to make a new login app by Xcode. I had been written my code but something goes wrong with it.
The code looks like to be correct but when debugging its skip from "Task" to the end of code , any help ?
Here is my code:
#IBAction func myButton(sender: AnyObject) { //login button
let UserName = input.text!
let UserPassword = password.text!
if ( UserName.isEmpty || UserPassword.isEmpty) { return }
//send data user to server side
let myUrl = NSURL(string: "http://servertest.cf/Store.php?LoginUser=Test%40home.com&LoginPassword=123456789")
let myRequest = NSMutableURLRequest(URL: myUrl!)
myRequest.HTTPMethod = "POST"
let postString = "email=\(UserName)&Password=\(UserPassword)";
myRequest.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let Task = NSURLSession.sharedSession().dataTaskWithRequest(myRequest)
{ data , response , error in
if error != nil {
println("error\(error)")
self.myLabel.text = "wrong user name"
}
var err : NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers , error: &err) as? NSDictionary
if let parseJson = json
{
var resultValue:String = parseJson["Status"] as! String!
println("result\(resultValue)")
if(resultValue == "Success" )
{
var storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var vc: UINavigationController = storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as! UINavigationController
self.presentViewController(vc, animated: true, completion: nil)
}
}
}
Task.resume()
}

The closure is queued to another queue and run in another thread. Add a breakpoint inside the closure if you want to run it line-by-line.

Related

AlertController view is not in the window hierarchy

i am a beginner in swift, i was trying to use an UIAlertController but i have got an error and the UiAlertController do not show up and i can see an error in the console that says
2021-06-20 18:16:28.494162+0200 Bicycall[50670:543648] [Presentation] Attempt to present <UIAlertController: 0x7fbaca034e00> on <Bicycall.login: 0x7fbabb01d800> (from <Bicycall.login: 0x7fbabb01d800>) whose view is not in the window hierarchy.
2021-06-20 18:16:28.494339+0200 Bicycall[50670:543648] [Presentation] Attempt to present <UIAlertController: 0x7fbac9862800> on <Bicycall.login: 0x7fbabb01d800> (from <Bicycall.login: 0x7fbabb01d800>) whose view is not in the window hierarchy.
Here what i have tried:
import UIKit
import CoreData
import AVKit
import AVFoundation
import TKSubmitTransition
class login: UIViewController {
#IBOutlet weak var passwordView: UIView!
#IBOutlet weak var emailView: UIView!
var id: Int?
var name: String?
var lastname: String?
var email:String?
var password:String?
var phone:String?
var u = ConnectedUser()
var BR = BaseUrl.baseUrl
var player: AVPlayer?
let videoURL: NSURL = Bundle.main.url(forResource: "Bikers", withExtension: "mp4")! as NSURL
func getTopMostViewController() -> UIViewController? {
var topMostViewController = UIApplication.shared.keyWindow?.rootViewController
while let presentedViewController = topMostViewController?.presentedViewController {
topMostViewController = presentedViewController
}
return topMostViewController
}
func presentTestAlert(_ title: String, _ message: String){
let alert = UIAlertController(title: title , message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .default, handler: { _ in
NSLog("The \"OK\" alert occured.")
}))
DispatchQueue.main.async {
self.getTopMostViewController()?.present(alert, animated: true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.DeleteAllData()
player = AVPlayer(url: videoURL as URL)
player?.actionAtItemEnd = .none
player?.isMuted = true
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
playerLayer.zPosition = -1
playerLayer.frame = view.frame
view.layer.addSublayer(playerLayer)
player?.play()
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem, queue: .main) { [weak self] _ in
self?.player?.seek(to: CMTime.zero)
self?.player?.play()
// Do any additional setup after loading the view.
}
emailView.layer.cornerRadius = 30.0
emailView.layer.borderWidth = 0.5
emailView.layer.borderColor = UIColor.white.cgColor
passwordView.layer.cornerRadius = 30.0
passwordView.layer.borderWidth = 0.5
passwordView.layer.borderColor = UIColor.white.cgColor
}
//widgets
#IBOutlet weak var txtEmail: UITextField!
#IBOutlet weak var txtPassword: UITextField!
//Actions
#IBAction func btnLogin(_ sender: Any){
//get
/*
guard let url = URL(string: "http://localhost:3000/bikes") else {
return
}
let session = URLSession.shared
session.dataTask(with: url) { ( data , response ,error) in
if let response = response {
print(response)
}
if let data = data {
print(data)
do
{
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
}catch{
print(error)
}
}
}.resume()
*/
//post
guard let url = URL(string: BR+"/login") else {
return
}
let bodyparameters = ["email": txtEmail.text, "password": txtPassword.text]
if (txtEmail.text!.isEmpty || txtPassword.text!.isEmpty ){
self.presentTestAlert("Wrong credentials","Email and Password must not be empty")
}else{
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: bodyparameters, options: []) else{
return
}
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data,response,error) in
let status = (response as! HTTPURLResponse).statusCode
//print(response)
print(status)
if let response = response {
let status = (response as! HTTPURLResponse).statusCode
//print(response)
print(status)
}
if((status) == 200){
self.presentTestAlert("Connection Success", " internet connection")
print(" Connection Successssssssssssssss")
if let data = data {
do {
//let json = try JSONSerialization.jsonObject(with: data, options: [])
// print(json);
print(data)
let user = try JSONDecoder().decode(User.self, from: data)
DispatchQueue.main.async {
self.id = user.user_id
self.name = user.name
self.lastname = user.lastname
self.email = user.email
self.password = user.password
self.phone = user.phone
print(self.id!)
print(self.email!)
if(user.user_id != 0){
self.saveUser()
self.DisplayConnectedUser()
self.performSegue(withIdentifier: "HomeSegue", sender: "nil")
}else{
self.presentTestAlert("Login Failed","Wrong credentials")
}
}
}catch{
print(error)
}
}
}else {
self.presentTestAlert("No Connection", "No internet connection")
print(" Connection Nooooooooooooooooooooooooo")
}
}.resume()
}
}
func DeleteAllData(){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let DelAllReqVar = NSBatchDeleteRequest(fetchRequest: NSFetchRequest<NSFetchRequestResult>(entityName: "Users"))
do {
try managedContext.execute(DelAllReqVar)
}
catch {
print(error)
}
}
func saveUser() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//represente l'ORM
let persistentContainer = appDelegate.persistentContainer
let managedContext = persistentContainer.viewContext
let entityDescription = NSEntityDescription.entity(forEntityName: "Users" , in: managedContext)
let object = NSManagedObject(entity: entityDescription! , insertInto: managedContext )
object.setValue(id! , forKey: "user_id" )
object.setValue(email! , forKey: "email" )
object.setValue(password! , forKey: "password" )
object.setValue(name! , forKey: "name" )
object.setValue(lastname! , forKey: "lastname" )
object.setValue(phone! , forKey: "phone" )
do {
try managedContext.save()
print("INSERT SUCCESSFULLY")
print(id!)
}
catch {
print("INSERT ERROR")
}
}
#IBAction func btnSignup(_ sender: Any) {
performSegue(withIdentifier: "signupSegue", sender: "nil")
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
}
func DisplayConnectedUser() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//represente l'ORM
let persistentContainer = appDelegate.persistentContainer
let managedContext = persistentContainer.viewContext //retourne NSManagedObject toujours
//la requete retourne un NSManagedObject
let request = NSFetchRequest<NSManagedObject>(entityName : "Users")
//execution de la requete
do {
let result = try managedContext.fetch(request)
for item in result {
print(item.value(forKey: "user_id") as! Int )
print(item.value(forKey: "email") as! String)
self.u.user_id = (item.value(forKey: "user_id") as! Int)
self.u.email = (item.value(forKey: "email") as! String)
self.u.password = (item.value(forKey: "password") as! String)
self.u.name = (item.value(forKey: "name") as! String)
self.u.lastname = (item.value(forKey: "lastname") as! String)
self.u.phone = (item.value(forKey: "phone") as! String)
print(self.u.user_id!)
print(self.u.email!)
print(self.u.password!)
print(self.u.name!)
print(self.u.lastname!)
print(self.u.phone!)
}
}
catch {
print("NO DATA FOUND , Error")
}
}
}
What is annoying me is that none of my alerts worked! i read some other answer in stackoverflow but the solutions did not work for me
What i am trying is to make my alerts working good
Any help will be so appreciated
It seems you want to present the alert over the video player (playerLayer) but you are calling your alert over the layer behind the playerLayer, it will give you the error that you're getting.
With reference to Swift 4 Attempt to present ViewController whose view is not in the window hierarchy
Add this function in your code
func getTopMostViewController() -> UIViewController? {
var topMostViewController = UIApplication.shared.keyWindow?.rootViewController
while let presentedViewController = topMostViewController?.presentedViewController {
topMostViewController = presentedViewController
}
return topMostViewController
}
And replace (Line 33)
self.present(alert, animated: true, completion: nil)
with
DispatchQueue.main.async {
getTopMostViewController()?.present(alert, animated: true, completion: nil)
}

Return response as object in swift

I have a function that connects to an API to retrieve data. The API takes two parameters accessCode (provided by user in a text box) and then UDID (UDID of their device). I can parse the data from within the function, but only locally. I need to store the values that are returned but am unsure on how to return them properly. Essentially I need this to return the json object as a dictionary (I think...) so it can be parsed outside of the async task. I've read through the swift documentation and that's where I found out how to do the requests, but I can't find a way to store the returned values in memory for access outside of the function.
func getResponse(accessCode:String, UDID:String, _ completion: #escaping (NSDictionary) -> ()) {
let urlPath = "https://apihosthere.com/api/validate?accessCode=" + accessCode + "&UDID=" + UDID
guard let url = URL(string: urlPath) else { return }
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
let results = jsonResult as? NSDictionary
print(results)
completion(results!)
}
} catch {
//Catch Error here...
}
}
task.resume()
}
First of all don't use NSDictionary in Swift, use native [String:Any] and declare the type as optional to return nil if an error occurs.
And never use .mutableContainers in Swift, the option is useless.
func getResponse(accessCode:String, UDID:String, completion: #escaping ([String:Any]?) -> Void)) {
let urlPath = "https://apihosthere.com/api/validate?accessCode=" + accessCode + "&UDID=" + UDID
guard let url = URL(string: urlPath) else { return }
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error else {
print(error)
completion(nil)
return
}
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
print(jsonResult)
completion(jsonResult)
} else {
completion(nil)
}
} catch {
print(error)
completion(nil)
}
}
task.resume()
}
Your mistake is that you don't consider the closure, you have to execute the entire code inside the completion handler
#IBAction func StartWizard(_ sender: UIButton) {
//Store entered access code
let accessCode = AccessCodeField.text!
//Call API to validate Access Code
getResponse(accessCode:accessCode, UDID:myDeviceUDID) { [weak self] result in
if let accessCodeFound = result?["Found"] as? Bool {
print("Value of Found during function:")
//If access code is valid, go to License view
print(accessCodeFound)
if accessCodeFound {
//Load License View
DispatchQueue.main.async {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let licenseController = storyboard.instantiateViewController(identifier: "LicenseViewPanel")
self?.show(licenseController, sender: self)
}
}
}
}
}
Your completion closure should handle the obtained data. You would call the function like this:
getResponse(accessCode: "code", UDID: "udid", completion: { result in
// Do whatever you need to do with the dictionary result
}
Also, I'd recommend you to change your NSDictionary with a swift Dictionary.
This is what the API returns as a response
{
AccessCode = 00000000;
Client = "0000 - My Company Name";
EmailAddress = "brandon#brandonthomas.me";
FirstName = Brandon;
Found = 1;
LastName = Thomas;
Status = A;
UDIDregistered = 1;
}
And this is what calls the function. I am calling at after clicking a button after an access code is being entered in a text field.
#IBAction func StartWizard(_ sender: UIButton) {
//Store entered access code
let accessCode = AccessCodeField.text!
var accessCodeFound: Bool? = nil
//Call API to validate Access Code
getResponse(accessCode:accessCode, UDID:myDeviceUDID) { result in
accessCodeFound = result["Found"] as! Bool
print("Value of Found during function:")
print(accessCodeFound)
//accessCodeFound = true
}
//If access code is valid, go to License view
print("Value of Found after function:")
print(accessCodeFound)
//accessCodeFound = nil ???
//it seems the value is getting reset after the function completes
if accessCodeFound == true{
//Load License View
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let licenseController = storyboard.instantiateViewController(identifier: "LicenseViewPanel")
self.show(licenseController, sender: Any?.self)
}
}

Accessing variables in protocol methods in swift

can anyone please help me with this swift code, i'm a swift beginner.
i'm trying to create a login page using MVC and it looks like this enter image description here
so when the user enters their login information and the status from the JSON data is "s" for a successful login it should display some test information, and when the login status is "f" for a failed login it should stay in the same login page, i'm trying to access the status in the protocol method in the code below:
so whenever the user presses the button it should take the required action but the status in the code below is nil so whenever i run the application the information is displayed wether the login was successful or not
//this piece of code is in the LoginViewController
func didReceivedLoginInfo(info : [LoginModel]) -> String
{
self.loginData = info
print("didReceivedLOOGIN count is \(loginData!.count)")//the print is successful here
for i in 0..<loginData!.count
{
print("LoginData Info : \(loginData![i])")//the print is successful here
}
statuss = loginData![0].status
print("HERE YOU GO, THIS IS WHAT I FOUND: \(statuss!)")//the print is successful here
return statuss!
}
//this piece of code is in the LoginViewController
func buttonAction(sender:UIButton!)
{
var btnsendtag: UIButton = sender
var uName = username!.text as? String!
var uPass = password!.text as? String!
parser = LoginParser()
parser!.getLoginInfo(uName!, pass: uPass!)
var status = loginData?[0].status
print("from View Controller this is the msg: \(status)")
parser!.delegate = self
if status == "s" {
print("from View Controller this is the status: \(status)")
let vc = ViewController()
let navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil)
}
else {
let vc = LoginViewController()
let navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil)
}
}
////this piece of code is in the LoginParser
import UIKit
#objc protocol LoginParserDelegate : NSObjectProtocol
{
func didReceivedLoginInfo (info : [LoginModel]) -> String
optional func didRecivedError()
}
class LoginParser: NSObject {
// var webData: NSMutableData?
var webData: NSData?
weak var delegate : LoginParserDelegate?
var name = String ()
var model : LoginModel?
var alertView:UIAlertView?
var MainLogin : [LoginModel] = []
func getLoginInfo (usern : String, pass : String){
var post:NSString = "LID=\(usern)&PWD=\(pass)&Passcode=s#v#"
var url:NSURL = NSURL(string: "some link")!
var postData:NSData = post.dataUsingEncoding(NSUTF8StringEncoding)!
var postLength:NSString = String( postData.length )
var 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 response: NSURLResponse?
let connection = NSURLConnection(request: request, delegate: self)
}
func connection(connection: NSURLConnection, didFailWithError error: NSError){
if delegate != nil {
if delegate!.respondsToSelector(Selector("didRecivedLoginInfo")){
delegate!.didRecivedError!()
}
}
}
func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse){
webData = NSData()
}
func connection(connection: NSURLConnection, didReceiveData data: NSData){
webData! = data
}
func connectionDidFinishLoading(connection: NSURLConnection){
let responseString = NSString(data: webData!, encoding: NSUTF8StringEncoding)
print("responseString \(responseString!)")
processUserTypes ()
}
func processUserTypes ()->[LoginModel]
{
model = LoginModel()
// Process JSON
do {
let result = try NSJSONSerialization.JSONObjectWithData(webData!, options: NSJSONReadingOptions.MutableContainers)as? NSDictionary
var Login = LoginModel()
let status = result?.objectForKey("Status") as? String
let msg = result?.objectForKey("En") as? String
let employeename=result?.objectForKey("DisplayName")as? String
print("STATUS IN PARSER IS \(status!)")
if status == "s"
{
print(status!)
Login.name = employeename
Login.status = status
Login.message = msg
alertView = UIAlertView()
alertView!.title = "Login successful"
alertView!.message = "Welcome \(employeename!)"
alertView!.delegate = self
alertView!.addButtonWithTitle("OK")
alertView!.show()
MainLogin.append(Login)
print("count in login is \(MainLogin.count)")
if delegate != nil
{
delegate!.didReceivedLoginInfo(MainLogin)
}
}
else
{
Login.message = msg
alertView = UIAlertView()
alertView!.title = "Login failed"
alertView!.message = msg!
alertView!.delegate = self
alertView!.addButtonWithTitle("OK")
alertView!.show()
MainLogin.append(Login)
print("this is the main login\(MainLogin)")
}
}
catch {
if delegate != nil {
if delegate!.respondsToSelector(Selector("didRecivedLoginInfo")){
delegate!.didRecivedError!()
}
}
}
return MainLogin
}
}
can anyone help me with this?
thanks
you call didReceivedLoginInfoinside processUserTypeswhich is called inside connectionDidFinishLoading. buttonAction calls getLoginInfowhich does an async request that will call back connectionDidFinishLoading when it is done.
this getLoginInfowill return a long time before the request is send out and a respone is received and connectionDidFinishLoading is called.
=> you cannot do anything after you call getLogininfo
=>
for you button method
create the parser
set the delegate
call getLoginInfo
dont do anything with potential results here
for the didReceiveLoginInfo.
you can do further logic and maybe even ui stuff there (you have to wrap logic that affects the ui in a
dispatch_async(dispatch_get_main_queue()){
//here
}
call

NSFetchRequest - entity - unexpectedly found nil while unwrapping an Optional value

I am currently working with Swift 2.0 and created a new "Master-Detail Application" in X-Code. I need that when the user clicks the BarButtomItem, a new View appears requesting a text field that will do a search in the internet.
The code to open the ViewController is as follows:
func insertNewObject(sender: AnyObject) {
let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let vc : ISBNRequest = mainStoryboard.instantiateViewControllerWithIdentifier("myISBN") as! ISBNRequest
presentViewController(vc, animated: true, completion: nil)
}
Once the user enters the text, and the search is finished, I need to add the results into to the TableView. To do this, Im calling an update function from the view Controller:
Function in ViewController:
#IBAction func buscarLibro(sender: AnyObject) {
print ("aqui estamos")
let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let mvc :MasterViewController = mainStoryboard.instantiateViewControllerWithIdentifier("myMVC") as! MasterViewController
var titulo : String = String()
var autores : [String] = [String]()
var portada : UIImage = UIImage()
let isbnTxt = ISBN.text!
let urls = "https://openlibrary.org/api/books?jscmd=data&format=json&bibkeys=ISBN"+isbnTxt
let url = NSURL(string: urls)
let datos:NSData? = NSData(contentsOfURL: url!)
if (datos == nil) {
//No hacer nada
print("datos nil")
} else {
//let texto = NSString(data:datos!, encoding: NSUTF8StringEncoding)
//self.textView.text = texto! as String
print("empieza busqueda")
do {
let json = try NSJSONSerialization.JSONObjectWithData(datos!, options: NSJSONReadingOptions.MutableLeaves)
let dico1 = json as! NSDictionary
print(dico1.allKeys)
var tmp = dico1["ISBN"+isbnTxt]
if (tmp != nil && tmp is NSDictionary) {
let dico2 = tmp as! NSDictionary
tmp = dico2["authors"]
if (tmp != nil && tmp is NSArray) {
let dico3 = tmp as! NSArray
titulo = (dico2["title"] as! NSString as String)
for id in dico3 {
print(id["name"])
autores.append(id["name"] as! NSString as String)
}
let cover = dico2["cover"]
if (cover != nil && cover is NSDictionary) {
let covers = cover as! NSDictionary
let url = NSURL(string: covers["medium"] as! NSString as String)
if let data = NSData(contentsOfURL: url!) {
portada = UIImage(data: data)!
}
}
print("LIBRO:" + titulo)
let libro : Libro = Libro(nombre : titulo,autores: autores, portada: portada)
mvc.libros.append(libro)
for x in mvc.libros {
print (x.nombre)
}
mvc.actualiza(libro)
}
}
} catch _ {
}
}
}
The mvc.actualiza function does the following:
func actualiza (libro:Libro) {
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context)
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
newManagedObject.setValue(libro as? AnyObject, forKey: "timeStamp")
// Save the context.
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
When executing the first line, in crashes here:
let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!)
And I am getting the following error message:
fatal error: unexpectedly found nil while unwrapping an Optional value
What am I missing to include in the transition from one view controller to another one?
That looks like self.managedObjectContext has not been initialised. You could try putting this before the faulting line to check:
print("managedObjectContext: \(self.managedObjectContext)")

How to call the view controller from another view controller programmatically depending on the response from the remote server

In my app I take the server credentials in the main view controller (loginViewController.swift). When I click on 'Login' button on the 'loginViewController', its shows the app logoViewController which has the activity indicator view and the credentials value is passed to the remote server over https connection. I get a JSON array in the response from remote server which consist of message "Successful : 1" or "Unsuccessful : 0" with other app details.
For the value '1' in the JSON array I want to show the menuViewController screen and for the value '0' I want to show the RegisterViewController screen for further process in the app.
Calling of 'menuViewController'/'RegisterViewController' should happen in the background process of the 'logoViewController'.
If have tried the following code given bellow, but unable to call the 'menuViewController'/'RegisterViewController'.
Please let me know were I went wrong. Is the UIStoryboard approach is right?
Any suggestion or links or tutorial will be helpful.
import UIKit
class logoViewController: UIViewController {
#IBOutlet weak var act: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
self.act.startAnimating()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// syncreq function is called from the connectionViewController.
// connectionViewController is the common class for connecting to the remote server
func syncreq (JSONdata: AnyObject) { // Proceesing for PRMS response
// Getting the value from the JSON
var Successful = self.getIntFromJSON(JSONdata as NSDictionary, key: "Successful")
println("Value of Successful : \(Successful)")
if (Successful == 0){
//let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("registrationID") as regVC
//self.navigationController?.pushViewController(secondViewController, animated: true)
//performSegueWithIdentifier("registrationID", sender: self)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("registrationID") as RegisterViewController
self.presentViewController(setViewController, animated: false, completion: nil)
}
else if (Successful == 1){
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("mnuID") as menuViewController
self.presentViewController(setViewController, animated: false, completion: nil)
}
}
func getIntFromJSON(data: NSDictionary, key: String) -> Int {
let info : AnyObject? = data[key]
// println("Value of data[key] : \(key)")
if let info = data[key] as? Int {
println("Value of value for \(key) : \(info)")
return info
}
else {
return 0
}
}
}
Thanks in advance
I have implemented a common function that will callback the calling function on the response from the remote server.
Following is the function which I have implemented.
func connect(jsonString:NSDictionary) -> NSDictionary
{
var JSONdata: AnyObject = ["" : ""] as Dictionary<String, String>
println("------------------Function connserv")
let prefs = NSUserDefaults.standardUserDefaults()
var conn_timeout: AnyObject = prefs.objectForKey("conn_timeout")!
var numberFormatter = NSNumberFormatter()
var number:NSNumber? = numberFormatter.numberFromString(conn_timeout as! String)
if let number = number {
var integer = Int(number)
println("\(integer)")
}
var recon_maxcount: AnyObject = prefs.objectForKey("recon_maxcount")!
println("recon_maxcount in Connection : \(recon_maxcount)")
println("conn_timeout in Connection : \(conn_timeout)")
var recon_interval: AnyObject = prefs.objectForKey("recon_interval")!
println("recon_interval in Connection : \(recon_interval)")
var number1:NSNumber? = numberFormatter.numberFromString(recon_maxcount as! String)
if let number1 = number1 {
var integer1 = Int(number1)
println("\(integer1)")
}
var number2:NSNumber? = numberFormatter.numberFromString(recon_interval as! String)
//if let number2 = number2 {
var integer2 = Int(number2!)
var xval = UInt32(integer2)
println("\(xval)")
//}
var IP: AnyObject = prefs.objectForKey("IP")!
var port: AnyObject = prefs.objectForKey("Port")!
println("IP in Connection : \(IP)")
println("port in Connection : \(port)")
prefs.synchronize()
println("HTTP request jsonString : \(jsonString)")
var request = NSMutableURLRequest(URL: NSURL(string: "https://\(IP):\(port)/")!)
var response: NSURLResponse?
var error: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(jsonString, options: nil, error: &error)
request.timeoutInterval = (number as! NSTimeInterval)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
//request.setValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("gzip", forHTTPHeaderField: "Accept-encoding")
println("Firing synchronous url connection......")
println(request)
//println("Before======\(i)!")
for (var i = 0; i < number1 as! Int ; i++)
{
var error: NSError?
println("Try connecting to server: \(NSDate())")
let urlData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
//println("response : \(response)")
//println("error : \(error)")
if error != nil || urlData!.length == 0
{
println("Error happend timeout======\(error?.code)!")
println(NSDate())
sleep(xval as UInt32)
//println("NSDate()")
JSONdata = ["0" : "0"] as Dictionary<String, String>
continue
}
else
{
println("Successfully connected : \(NSDate())")
println("\(urlData!.length) bytes of data was returned")
println(response!);
if let httpResponse = response as? NSHTTPURLResponse {
println("Status Code ------------------------------------>\(httpResponse.statusCode)")
}
println(NSString(data: urlData!, encoding: NSUTF8StringEncoding)!)
var er: NSError?
let JSONresdata: AnyObject = (NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers,error: &er)!)
println("==========================================================================================")
println("JSON response : \(JSONresdata)")
JSONdata = JSONresdata as! NSDictionary
break
}
}
println("out of for loop : \(JSONdata)")
return JSONdata as! NSDictionary;
}