in this i am getting the value through webservice. it's getting the value perfectly. for testing i used print statement and it's showing prefect values, but when i am assigning those values to variable it's not assgning on second click my variable are getting the values.. first time it goes in else, however it should go in if.
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
if error != nil
{
print("Error")
}
else
{
if let content = data
{
do
{
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let asd = myJson.value(forKey: "signinResult")
print(asd!)
self.answer = String(describing: asd!)
var mystring = self.answer.components(separatedBy:"\"")
var mystrin = [String]()
let size = mystring.count
var i = 0
while (i < size-1 )
{
let st1 = mystring[i+1]
mystrin = st1.components(separatedBy:",")
self.em = mystrin[0]
print(self.em)
self.pw = mystrin[1]
print(self.pw)
self.na = mystrin[2]
print(self.na)
self.num = mystrin[3]
print (self.num)
i += 2
}
}
catch
{
}
}
}
task.resume()
if email.text == em && pwd.text == pw
{
GlobalVariable.myString=em
GlobalVariable.name=na
GlobalVariable.number=num
GlobalVariable.pwd = pw
GlobalVariable.i=1
self.performSegue(withIdentifier: "segue", sender: nil)
}
else
{
let alert = UIAlertController(title: "Alert", message: "Wrong Email and password", preferredStyle:UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert,animated: true, completion: nil)
}
You set value of that variable in web service block but using it outside the block so first time it doesn't have value to show when you click send time meanwhile web service response and value assign to that variable so get it.
The code should be like this.
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
if error != nil
{
print("Error")
}
else
{
if let content = data
{
do
{
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let asd = myJson.value(forKey: "signinResult")
print(asd!)
self.answer = String(describing: asd!)
var mystring = self.answer.components(separatedBy:"\"")
var mystrin = [String]()
let size = mystring.count
var i = 0
while (i < size-1 )
{
let st1 = mystring[i+1]
mystrin = st1.components(separatedBy:",")
self.em = mystrin[0]
print(self.em)
self.pw = mystrin[1]
print(self.pw)
self.na = mystrin[2]
print(self.na)
self.num = mystrin[3]
print (self.num)
i += 2
}
if email.text == em && pwd.text == pw
{
GlobalVariable.myString=em
GlobalVariable.name=na
GlobalVariable.number=num
GlobalVariable.pwd = pw
GlobalVariable.i=1
self.performSegue(withIdentifier: "segue", sender: nil)
}
else
{
let alert = UIAlertController(title: "Alert", message: "Wrong Email and password", preferredStyle:UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert,animated: true, completion: nil)
}
}
catch
{
}
}
}
task.resume()
Related
I'm working on my app (iOS) to get AdMob and AdSense earnings information. But I've been having trouble getting specifics from them. I've already created the credentials and client ID from my Google account, but I'm not sure where to put them.
I tried carefully following many methods from this link but was never successful.
My first step: During startup, check to see if you are logged in or out.
import FirebaseAuth
import GoogleSignIn
var currentPID = ""
func checkGoogleAccountStatus() {
GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
if error != nil || user == nil {
print("Signed out")
self.loginButton()
} else {
print("Signed in")
let userAccess: String = user!.authentication.accessToken
self.googledSignedInSuccess(googleToken: userAccess, tokenID: user!.authentication.idToken!)
let dateformatter = DateFormatter()
dateformatter.dateFormat = "MMMM d, yyyy h:mm:ss a"
let expiredToken = user?.authentication.accessTokenExpirationDate
print("Token Expired: \(dateformatter.string(from: expiredToken!))")
}
}
}
Successful
My second step: When I tapped the button to log in, an alert controller appeared to see if the log in was successful. It will display the alert controller's profile picture, name, and email address.
#objc func loginTapped() {
let adMobScope = "https://www.googleapis.com/auth/admob.report"
let adSenseScope = "https://www.googleapis.com/auth/adsensehost"
let additionalScopes = [adMobScope,adSenseScope]
let signInConfig = GIDConfiguration.init(clientID: "<My URL Schemes>")
GIDSignIn.sharedInstance.signIn(with: signInConfig, presenting: self, hint: nil, additionalScopes: additionalScopes) { user, error in
guard error == nil else { return }
guard let user = user else { return }
if let profiledata = user.profile {
let grantedScopes = user.grantedScopes
if grantedScopes == nil || !grantedScopes!.contains(adMobScope) {
print("AdMob not Granted...")
} else {
print("AdMob Granted!")
}
if grantedScopes == nil || !grantedScopes!.contains(adSenseScope) {
print("AdSense not Granted...")
} else {
print("AdSense Granted!")
}
//let userId: String = user.userID ?? ""
let givenName: String = profiledata.givenName ?? ""
let familyName: String = profiledata.familyName ?? ""
let email: String = profiledata.email
let userToken: String = user.authentication.idToken!
let userAccess: String = user.authentication.accessToken
let credential = GoogleAuthProvider.credential(withIDToken: userToken, accessToken: userAccess)
Auth.auth().signIn(with: credential) { result, error in
if let error = error {
print(error.localizedDescription)
let alert = UIAlertController(title: "Error", message: "Something went wrong, please try again.", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: {_ in return })
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
if let imgurl = user.profile?.imageURL(withDimension: 300) {
let absoluteurl: String = imgurl.absoluteString
let alert = UIAlertController(title: "\(givenName) \(familyName)", message: "\n\n\n\n\n\n\n\(email)\nLogin Successful", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: {_ in
// MARK: Do something to update
self.checkGoogleAccountStatus()
})
let imgViewTitle = UIImageView()
imgViewTitle.translatesAutoresizingMaskIntoConstraints = false
imgViewTitle.layer.borderColor = UIColor(named: "Font Color")?.cgColor
imgViewTitle.layer.borderWidth = 3
imgViewTitle.layer.cornerRadius = 50
imgViewTitle.clipsToBounds = true
alert.view.addSubview(imgViewTitle)
imgViewTitle.centerYAnchor.constraint(equalTo: alert.view.centerYAnchor, constant: -28).isActive = true
imgViewTitle.centerXAnchor.constraint(equalTo: alert.view.centerXAnchor).isActive = true
imgViewTitle.widthAnchor.constraint(equalToConstant: 100).isActive = true
imgViewTitle.heightAnchor.constraint(equalToConstant: 100).isActive = true
DispatchQueue.global().async {
if let data = try? Data(contentsOf: URL(string: absoluteurl)! ) { if let image = UIImage(data: data) { DispatchQueue.main.async { imgViewTitle.image = image } } }
}
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
} else {
let alert = UIAlertController(title: "\(givenName) \(familyName)", message: "\(email)\nLogin Successful", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: {_ in
// MARK: Do something to update
self.checkGoogleAccountStatus()
})
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
}
}
}
When I logged in, it asked for permission to access AdMob and AdSense, followed by a pop-up alert that said I had successfully logged in.
My third step: Getting the PID from Google AdMob / AdSense
import CurlDSL
import Gzip
func googledSignedInSuccess(googleToken: String, tokenID: String) {
guard let url = URL(string: "https://admob.googleapis.com/v1/accounts/") else { return }
do {
try CURL(#"curl -H "Authorization: Bearer \#(googleToken)" "\#(url)""#).run { data, response, error in
if let error = error { print("Error took place \(error)"); return }
if let response = response as? HTTPURLResponse {
if response.statusCode != 200 {
print("Error: \(response)")
} else {
if let data = data {
do {
if let rawJSON = try? JSONDecoder().decode(GetAdMobInfo.self, from: data) {
currentPID = rawJSON.account[0].publisherID
print("Successful: \(currentPID)")
self.adMob_gettingReport(pid: currentPID, token: googleToken)
}
}
}
}
}
}
} catch { print("Failed.") }
}
struct GetAdMobInfo: Codable {
let account: [Account]
}
struct Account: Codable {
let name, publisherID, reportingTimeZone, currencyCode: String
enum CodingKeys: String, CodingKey {
case name
case publisherID = "publisherId"
case reportingTimeZone, currencyCode
}
}
It was success, I was able to get my PID and writed to currentPID as string.
My final step, which failed:
func adMob_gettingReport(pid: String, token: String) {
guard let url = URL(string: "https://admob.googleapis.com/v1/accounts/\(pid)/mediationReport:generate") else { return }
let reportData = "--data #- << EOF {\"report_spec\": {\"date_range\": {\"start_date\": {\"year\": 2020, \"month\": 4, \"day\": 1}, \"end_date\": {\"year\": 2020, \"month\": 4, \"day\": 1} },\"dimensions\": [\"AD_SOURCE\", \"AD_UNIT\", \"PLATFORM\"], \"metrics\": [\"ESTIMATED_EARNINGS\"]}} EOF"
do {
try CURL(#"curl -X POST "\#(url)" -H "Authorization: Bearer \#(token)" -H "Content-Type: application/json" \#(reportData)"#).run { data, response, error in
if let error = error { print("Error took place \(error)"); return }
if let response = response as? HTTPURLResponse {
if response.statusCode != 200 {
print("Error: \(response)")
} else {
if let data = data {
print("Getting AdMob Successful")
let decompressedData: Data
if data.isGzipped { decompressedData = try! data.gunzipped() }
else { decompressedData = data }
var getLineFromString: [String] = []
getLineFromString += String(data: decompressedData, encoding: .utf8)!.components(separatedBy: "\n")
for checkLine in getLineFromString {
print("Line: \(checkLine)")
}
}
}
}
}
} catch { print("Failed.") }
}
Attempting to obtain earnings information from AdMob and AdSense, but it kept saying failing in print. This is where I've been for nearly two months. What did I overlook?
Attempting to read our web service into a UITableViewController and it only returns the first record to the simulator. So hoping that someone will be able to look at the code and guide me down the correct path. Ultimate goal is to get it into a UITableViewCell so I can format nicely but just looking to get all the records.
Here is a view of the partial json file that will be returned.
{
"Count":11518,
"Result":[
{
"cuName": "#1",
"charter_Num":
"16328","City":
"Jonesboro",
"State_id": "GA",
"cuName_location": "#1 - Jonesboro, GA"
},
{
"cuName": "#lantec Financial",
"charter_Num": "7965",
"City": "Virginia Beach",
"State_id": "VA",
"cuName_location": "#lantec Financial - Virginia Beach, VA"
}]
}
Here is the code that reads in the json web service and attempts to parse and put in the table.
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
}
//Commented out the following lines because it doesn't return anything when using the modified code that works
//
// guard let data_list = json as? NSArray else
// {
// return
// }
//This code works but only gives me the 1st record back
if let cu_list = try? json as? [String:Any],
let result = cu_list?["Result"] as? [[String:Any]],
let charter_num = result[0]["charter_Num"] as? String,
let value = result[0]["cuName_location"] as? String, result.count > 0 {
TableData.append(value + " (" + charter_num + ")")
} else {
print("bad json - do some recovery")
}
DispatchQueue.main.async(execute: {self.do_table_refresh()})
}
You are referring the 0th index element from result object and it will only return the 1st record from JSON data. You need to run thru the loop and append the data to array which you need to use for populating the data in UITableView.
func GetCategoryData(){
//get_high_score.php?from=1472409001482&number=10&to=1493657787867
let checklaun = UserDefaults.standard.integer(forKey: "Language")
if checklaun == 1 {
EZLoadingActivity.show("Loading...", disableUI: false)
}else{
EZLoadingActivity.show("جار التحميل...", disableUI: false)
}
DispatchQueue.global(qos: .background).async {
let myUrl = URL(string: GlobleUrl.BASEURL + "advertise_list.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "GET"
// let fromvalue = 1472409001482
// let numbervalue = 10
// let tovalue = 1493657787867
let postString = ""//"from=" + fromvalue + "&" + "number=" + numbervalue + "&" + "to=" + tovalue
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
EZLoadingActivity.hide(false, animated: true)
print("error=\(error)")
let checklaun = UserDefaults.standard.integer(forKey: "Language")
var titlemsga : String = String()
var okmsg : String = String()
if checklaun == 1 {
titlemsga = "Something going wrong"
okmsg = "Ok"
}else{
titlemsga = "حدث خطأ ما"
okmsg = "حسنا"
}
let alert = UIAlertController(title: "", message: titlemsga, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: okmsg, style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
print("response = \(response)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
DispatchQueue.main.async {
if let parseJSON = json {
print(parseJSON)
let status = parseJSON["status"] as! Bool
if status == true{
EZLoadingActivity.hide(true, animated: false)
self.categoryDataArray = parseJSON["data"] as! NSMutableArray
print("\(self.categoryDataArray)")
self.filterarray = parseJSON["fixed_cat"] as! NSMutableArray
let teamp = self.categoryDataArray .value(forKey: "main_image") as AnyObject
print("\(teamp)")
self.categoryImageArray.setArray(teamp as! [Any])
print("\( self.categoryImageArray)")
// let teamp = self.data .value(forKey: "name") as AnyObject
// print("\(teamp)")
// self.categoryNameArray.setArray(teamp as! [Any])
self.allcategoryTableViewCell.reloadData()
self.allcategoryfilterlistview.reloadData()
// self.tblscoreList.reloadData()
}else{
EZLoadingActivity.hide(false, animated: true)
}
}
}
}
catch {
EZLoadingActivity.hide(false, animated: true)
let checklaun = UserDefaults.standard.integer(forKey: "Language")
var titlemsga : String = String()
var okmsg : String = String()
if checklaun == 1 {
titlemsga = "Something going wrong"
okmsg = "Ok"
}else{
titlemsga = "حدث خطأ ما"
okmsg = "حسنا"
}
let alert = UIAlertController(title: "", message: titlemsga, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: okmsg, style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
print(error)
}
}
task.resume()
}
}
I'm currently trying to get a value from an alert box in swift 3.
The below code is used to prompt the alert and save the data, however, im having trouble with calling back the data and manipulating it so it's just a basic string.
func presentAlert() {
let alertController = UIAlertController(title: "IP?", message: "Please input your unique key:", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
if let field = alertController.textFields?[0] {
// store it
UserDefaults.standard.set(field.text, forKey: "userIP")
UserDefaults.standard.synchronize()
} else {
// user did not fill field
print("no input given")
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alertController.addTextField { (textField) in
textField.placeholder = "IP"
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
This method is called here:
override func viewDidAppear(_ animated: Bool) {
presentAlert()
}
I'm trying to call it and assign it in between a string as:
let url_to_unlock:String = "http://\(UserDefaults.standard.value(forKey: "userIP")):3000/unLock"
However, this gives me the output:
http://Optional():3000/unLock
When I try to print it.
Any nudge in the correct direction would be greatly appreciated.
Class Added:
class ViewController: UIViewController {
func presentAlert() {
let alertController = UIAlertController(title: "IP?", message: "Please input your unique key:", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
if let field = alertController.textFields?[0] {
// store your data
//this could be lock unique key name etc in future
UserDefaults.standard.set(field.text, forKey: "userIP")
UserDefaults.standard.synchronize()
} else {
// user did not fill field
print("no input given")
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alertController.addTextField { (textField) in
textField.placeholder = "IP"
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
//view did appear for the alert
override func viewDidAppear(_ animated: Bool) {
presentAlert()
}
//to post to an /unLock it must be put in the URL
// let url_to_unlock:String = "http://\(UserDefaults.standard.value(forKey: "userIP")):3000/unLock"
//let url_to_lock:String = "http://\(textField):3000/Lock"
let url_to_unlock:String = "http://10.73.195.218:3000/unLock"
let url_to_lock:String = "http://10.73.195.218:3000/Lock"
override func viewDidLoad() {
super.viewDidLoad()
}
var Timestamp: String {
return "\(NSDate().timeIntervalSince1970 * 1000)"
}
func un_lock()
{
print(url_to_unlock)
let url:URL = URL(string: url_to_unlock)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let paramString = "data=unLocking at \(Timestamp)"
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
print("error")
return
}
//for errors
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print(dataString! )
})
task.resume()
}
func lock()
{
let url:URL = URL(string: url_to_lock)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let paramString = "data=Locking at \(Timestamp)"
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
print("error")
return
}
//for errors
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print(dataString! )
})
task.resume()
}
#IBAction func lock(_ sender: UIButton) {
lock()
}
#IBAction func unLock(_ sender: Any) {
un_lock()
}
}
Thank you.
The value for this is optional:
// let url_to_unlock:String = "http://\(UserDefaults.standard.value(forKey: "userIP")):3000/unLock"
try:
let url = UserDefaults.standard.value(forKey: "userIP")!
let url_to_unlock:String = "http://\(url):3000/unLock"
I am trying to pass a users' email address to another ViewController via a delegate when the user has successfully logged in.
The snippet of code in question (marked *) works fine where it is and the data is passed successfully. However, at this point the user has not successfully logged in, therefore I would rather insert the snippet where the /**** is, a little further down.
However it does work when in that position. Why is that? (I am new to Swift)
Thanks
#IBAction func loginButtonTapped(_ sender: AnyObject)
{
let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;
if (userPassword!.isEmpty || userEmail!.isEmpty) { return; }
// send user data to server side
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/userLogin.php");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "email=\(userEmail!)&password=\(userPassword!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
// spinningActivity!.hide(true)
if(error != nil)
{
//Display an alert message
let myAlert = UIAlertController(title: "Alert", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
*if self.delegate != nil {
self.delegate?.userLoggedIn(data: userEmail! )
}
// retrieve login details and check to see if all ok
if let parseJSON = json {
let returnValue = parseJSON["status"] as? String
if(returnValue != "error")
{
/**** if self.delegate != nil {
self.delegate?.userLoggedIn(data: userEmail! )
} ****/
UserDefaults.set(UserDefaults.standard)(true, forKey: "isUserLoggedIn");
let mainPage = self.storyboard?.instantiateViewController(withIdentifier: "ViewController")
let mainPageNav = UINavigationController(rootViewController: mainPage!)
let appDelegate = UIApplication.shared.delegate
appDelegate?.window??.rootViewController = mainPageNav
self.dismiss(animated: true, completion: nil)
} else {
// display an alert message
let userMessage = parseJSON["message"] as? String
let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}
}
} catch
{
print(error)
}
}
}
I am trying to return a result from a JSON object but unable to do so. I am new to Swift so kindly explain me how to do so. In the below code I want to return json_level_number in the return of function fetchNumberOfSections () where i have hard coded as 5 right now return 5. If i declare a variable json_level_number just above the reachability code it sort of solves the problem but then it is returning '0' for the first time. The API returns 2 each time.
Code as below:
func fetchNumberOfSections () -> Int {
if Reachability.isConnectedToNetwork() == true {
// Below code to fetch number of sections
var urlAsString = "http://themostplayed.com/rest/fetch_challenge_sections.php"
urlAsString = urlAsString+"?apiKey="+apiKey
print (urlAsString)
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
print(error!.localizedDescription)
}
do {
let jsonResult = (try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
let json_level_number: String! = jsonResult["level_number"] as! String
//
dispatch_async(dispatch_get_main_queue(), {
// self.dateLabel.text = jsonDate
// self.timeLabel.text = jsonTime
print(json_level_number)
// self.activityIndicatorStop()
})
}
catch let errorJSON {
print (errorJSON)
// alert box code below
let alert = UIAlertController(title: "JSON Error!", message:"Error processing JSON.", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default) { _ in
// Put here any code that you would like to execute when
self.dismissViewControllerAnimated(true, completion: {})
}
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
// alert box code end
}
})
jsonQuery.resume()
// End
}
else {
print("Internet connection FAILED")
self.performSegueWithIdentifier("nointernet", sender: nil)
}
return 5
}