How can I keep the value of a variable outside a function? - json

I'm trying to display the value I get from a JSON in an AR text, within the DecodeJSON function it all works, I even achieve to put that value in a normal label but when I try to set that value to the AR text it is empty... what can I do or what I'm doing wrong? It would be very useful if you can help me out with this.
#IBOutlet var sceneView: ARSCNView!
#IBOutlet weak var labelTest: UILabel!
let URL_VWC = "http://w1.doomdns.com:11000/restaguapotable/api/celula/10/sitio/4";
var name :String!
struct JSONTest: Codable {
let Nombre: String
let Tiempo: String
}
override func viewDidLoad() {
super.viewDidLoad()
// Set the view's delegate
sceneView.delegate = self
// Show statistics such as fps and timing information
sceneView.showsStatistics = true
// Create a new scene
let scene = SCNScene()
// Set the scene to the view
sceneView.scene = scene
DecodeJson();
let text = SCNText(string: name, extrusionDepth: 1.0)
text.firstMaterial?.diffuse.contents = UIColor.black
let textNode = SCNNode(geometry: text)
textNode.position = SCNVector3(0,0, -0.5)
textNode.scale = SCNVector3(0.02,0.02,0.02)
sceneView.scene.rootNode.addChildNode(textNode)
}
func DecodeJson(){
guard let url = URL(string: URL_VWC) else { return }
// 2
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
do {
// 3
//Decode data
let JSONData = try JSONDecoder().decode(JSONTest.self, from: data)
// 4
//Get back to the main queue
DispatchQueue.main.async {
self.name = JSONData.Nombre
self.labelTest.text = self.name
}
} catch let jsonError {
print(jsonError)
}
// 5
}.resume()
}

This means that DecodeJson() returns self.name = JSONData.Nombre after let text = SCNText(string: name, extrusionDepth: 1.0) is called.
You should have a separate function where you setup your scene after the DecodeJson() has returned the JSON

Related

How to Parse JSON data from a URL and append to a UiLabel with Swift 5

I am trying to get data from Json url for this specific line "ConfirmedCount" from https://raw.githubusercontent.com/BlankerL/DXY-COVID-19-Data/master/json/DXYOverall.json to a UiLabel that I created but keeps getting error. I have been trying to do this for week now.
Here is my code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var labeltest: UILabel!
//the json file url
let URL_HEROES = "https://raw.githubusercontent.com/BlankerL/DXY-COVID-19-Data/master/json/DXYOverall.json";
//the label we create
#IBOutlet weak var labelTest: UILabel!
//A string array to save all the names
var nameArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
//calling the function that will fetch the json
getJsonFromUrl()
}
//this function is fetching the json from URL
func getJsonFromUrl(){
//creating a NSURL
let url = NSURL(string: URL_HEROES)
//fetching the data from the url
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
//printing the json in console
print(jsonObj.value(forKey: "results")!)
//getting the avengers tag array from json and converting it to NSArray
if let heroeArray = jsonObj.value(forKey: "results") as? NSArray {
//looping through all the elements
for results in heroeArray{
//converting the element to a dictionary
if let heroeDict = results as? NSDictionary {
var confirmedCount: Int
//getting the name from the dictionary
if let confirmedCount = heroeDict.value(forKey: "confirmedCount") {
//adding the name to the array
self.nameArray.append((String (format: "1234", confirmedCount as! Int)))
}
}
}
}
OperationQueue.main.addOperation({
//calling another function after fetching the json
//it will show the names to label
self.showNames()
})
}
}).resume()
}
func showNames(){
//looping through all the elements of the array
for confirmedCount in nameArray{
labelTest.text = (confirmedCount)
}
}
}
This is the error that I am getting:
(
{
abroadRemark = "";
confirmedCount = 80422;
confirmedIncr = 120;
curedCount = 49923;
curedIncr = 2663;
currentConfirmedCount = 27515;
currentConfirmedIncr = "-2581";
deadCount = 2984;
deadIncr = 38;
generalRemark = "\U7591\U4f3c\U75c5\U4f8b\U6570\U6765\U81ea\U56fd\U5bb6\U536b\U5065\U59d4\U6570\U636e\Uff0c\U76ee\U524d\U4e3a\U5168\U56fd\U6570\U636e\Uff0c\U672a\U5206\U7701\U5e02\U81ea\U6cbb\U533a\U7b49";
note1 = "\U75c5\U6bd2\Uff1aSARS-CoV-2\Uff0c\U5176\U5bfc\U81f4\U75be\U75c5\U547d\U540d COVID-19";
note2 = "\U4f20\U67d3\U6e90\Uff1a\U65b0\U51a0\U80ba\U708e\U7684\U60a3\U8005\U3002\U65e0\U75c7\U72b6\U611f\U67d3\U8005\U4e5f\U53ef\U80fd\U6210\U4e3a\U4f20\U67d3\U6e90\U3002";
note3 = "\U4f20\U64ad\U9014\U5f84\Uff1a\U7ecf\U547c\U5438\U9053\U98de\U6cab\U3001\U63a5\U89e6\U4f20\U64ad\U662f\U4e3b\U8981\U7684\U4f20\U64ad\U9014\U5f84\U3002\U6c14\U6eb6\U80f6\U4f20\U64ad\U548c\U6d88\U5316\U9053\U7b49\U4f20\U64ad\U9014\U5f84\U5c1a\U5f85\U660e\U786e\U3002";
remark1 = "\U6613\U611f\U4eba\U7fa4\Uff1a\U4eba\U7fa4\U666e\U904d\U6613\U611f\U3002\U8001\U5e74\U4eba\U53ca\U6709\U57fa\U7840\U75be\U75c5\U8005\U611f\U67d3\U540e\U75c5\U60c5\U8f83\U91cd\Uff0c\U513f\U7ae5\U53ca\U5a74\U5e7c\U513f\U4e5f\U6709\U53d1\U75c5";
remark2 = "\U6f5c\U4f0f\U671f\Uff1a\U4e00\U822c\U4e3a 3\Uff5e7 \U5929\Uff0c\U6700\U957f\U4e0d\U8d85\U8fc7 14 \U5929\Uff0c\U6f5c\U4f0f\U671f\U5185\U53ef\U80fd\U5b58\U5728\U4f20\U67d3\U6027\Uff0c\U5176\U4e2d\U65e0\U75c7\U72b6\U75c5\U4f8b\U4f20\U67d3\U6027\U975e\U5e38\U7f55\U89c1";
remark3 = "\U5bbf\U4e3b\Uff1a\U91ce\U751f\U52a8\U7269\Uff0c\U53ef\U80fd\U4e3a\U4e2d\U534e\U83ca\U5934\U8760";
remark4 = "";
remark5 = "";
seriousCount = 6416;
seriousIncr = "-390";
suspectedCount = 520;
suspectedIncr = 143;
updateTime = 1583295001876;
}
)
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file /Users/AbdalQaydi/Desktop/jnews/jnews/ViewController.swift, line 84
2020-03-04 00:26:49.829895-0500 jnews[12702:1192396] Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file /Users/AbdalQaydi/Desktop/jnews/jnews/ViewController.swift, line 84
(lldb)
It looks like it can parse the data but I don't know how to add the json data for line "confirmedCount" to label.
Please any help is really appreciated. I have been trying to figure out how to do this and just can't find a way.
Use Codable to parse the JSON data.
Models:
struct Root: Decodable {
let results: [Result]
let success: Bool
}
struct Result: Decodable {
let currentConfirmedCount, confirmedCount, suspectedCount, curedCount: Int
let deadCount, seriousCount, currentConfirmedIncr, confirmedIncr: Int
let suspectedIncr, curedIncr, deadIncr, seriousIncr: Int
let generalRemark, abroadRemark, remark1, remark2: String
let remark3, remark4, remark5, note1: String
let note2, note3: String
let updateTime: Int
}
Parse the data like,
if let url = URL(string: URL_HEROES) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let data = data {
do {
let response = try JSONDecoder().decode(Root.self, from: data)
let confirmedCountArr = response.results.map { String($0.confirmedCount) }
nameArray.append(contentsOf: confirmedCountArr)
//rest of the code...
} catch {
print(error)
}
}
}.resume()
}

optional type String? not unwrapped

I have a PHP page that is on my webserver that interacts with a mysql database called grabmapinfo.php
The output of the page is [{"companyname":"Brunos Burgers","companyphone":"7745632382","companytown":"858 Western Ave, Lynn, MA 01905"}]
Now I have this Swift code, which I want to get the info from the database, geocode the address to latitude and longitude, plot the annotation on the map, change the annotation image and title, and make a circle with a radius of 5 with the pin being in the center.
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.buyerMapView1.showsUserLocation = true
let url = NSURL(string: "https://alanr917.000webhostapp.com/grabmapinfo.php")
var request = URLRequest(url:url! as URL)
URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) -> Void in
if error != nil {
// Display an alert message
print(error)
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [[String:AnyObject]] {
for item in json {
// Get company info from DB
let companyname = item["companyname"] as? String
let companyphone = item["companyphone"] as? String
let companytown = item["companytown"] as? String
print("Company : \(companyname)")
print("Phone : \(companyphone)")
print("Address : \(companytown)")
let address = companytown
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address, completionHandler: {
(placemarks: [AnyObject]!, error: NSError!) -> Void in
if let placemark = placemarks?[0] as? CLPlacemark {
let pa = MKPointAnnotation()
pa.coordinate = placemark.location.coordinate
pa.title = companyname
pa.imageName = #imageLiteral(resourceName: "growerAnnotation")
self.buyerMapView1.addAnnotation(pa)
let center = annotation.coordinate
let circle = MKCircle(center: center, radius: 5) // change the 5 later to however many miles the grower purchased
self.buyerMapView1.add(circle)
}
})
}
}
} catch {
print(error)
}
})
}
But i get an error that says the optional type String? is not unwrapped and it errors out and wont build.
Does anyone see where I'm going wrong? Thanks!
companyTown is declared as an optional string and the geocodeAddressString method takes a string. You need to unwrap the option before calling it.
if let addressUnwrapped = address {
geocoder.geocodeAddressString(addressUnwrapped, completionHandler: {
(placemarks: [AnyObject]!, error: NSError!) -> Void in
...
})
}
Please check the comments through the code for more detailed explanation on the problems that I found in your code:
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var buyerMapView1: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
buyerMapView1.showsUserLocation = true
// first unwrap your url
guard let url = URL(string: "https://alanr917.000webhostapp.com/grabmapinfo.php") else { return }
print("url:",url)
// no need to create a request. just a url is fine and you don't need to specify the parameters type. Let the compiler infer it.
URLSession.shared.dataTask(with: url) { data, response, error in
// unwrap your data and make sure there is no error
guard let data = data, error == nil else {
print(error ?? "nil")
return
}
// you should update the UI from the main queue
DispatchQueue.main.async {
print("data:", data)
do {
if let array = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] {
for dict in array {
// make sure you unwrap your dictionary strings
let companyname = dict["companyname"] as? String ?? ""
let companyphone = dict["companyphone"] as? String ?? ""
let companytown = dict["companytown"] as? String ?? ""
print("Company:", companyname)
print("Phone:", companyphone)
print("Address:", companytown)
let address = companytown
let geocoder = CLGeocoder()
// again let the compiler infer the types vvv vvv
geocoder.geocodeAddressString(address) { placemarks, error in
if let placemark = placemarks?.first,
let coordinate = placemark.location?.coordinate {
let pa = MKPointAnnotation()
pa.coordinate = coordinate
pa.title = companyname
self.buyerMapView1.addAnnotation(pa)
let center = pa.coordinate // where does this coordinate come from??
let circle = MKCircle(center: center, radius: 5)
self.buyerMapView1.add(circle)
}
}
}
}
} catch {
print(error)
}
}
// you forgot to call resume to start your data task
}.resume()
}
}

Alamofire download from JSON API

I'm trying to set text on a label from api, but it seems that the function doesn't even get called. Please refer to the snippet below. Is there anything wrong with it?
EDIT: typealias DownloadComplete = () -> ()
var date: String = ""
override func viewDidLoad() {
super.viewDidLoad()
timeLbl.text = date
// Do any additional setup after loading the view.
}
func downloadTimeData(completed: #escaping DownloadComplete) {
//Downloading forecast weather data for TableView
Alamofire.request(APIURL).responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject> {
if let currentDate = dict["fulldate"] as? String {
self.date = currentDate
print(self.date)
print("xxx")
}
}
completed()
}
}
I figured it out with simpler and easier way, through the alamofire documetation.
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(APIURL).responseJSON { response in
print(response.result) // result of response serialization
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject> {
let currentDate = dict["fulldate"] as? String
self.timeLbl.text = currentDate
}
}
}
In the code you posted you are not calling downloadTimeData(completed:) anywhere.
You can do that in viewDidAppear(_:) for example:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
downloadTimeData {
// The request has completed
timeLbl.text = date
}
}
Note that you may need to change the call slightly, depending on how DownloadComplete is defined.
You are setting timeLbl.text immediately on page load in viewDidLoad, but you haven't told the app to do anything else.
You have to move downloadTimeData to viewDidLoad, and in the completion, set 'timeLbl.text = date'
You have to set some sort of text place holder or loader while your call is being made, because you can't guarantee that it is instant.
Are we setting one label? Or a whole tableview of labels?
I changed some syntax to be "swiftier"
var date = ""
override func viewDidLoad() {
super.viewDidLoad()
//call downloadTimeData here
downloadTimeData() {
//once we are in completion, this means internet call finished, so set label now
self.timeLbl.text = date
}
}
func downloadTimeData(completed: #escaping DownloadComplete) {
//Downloading forecast weather data for TableView
Alamofire.request(APIURL).responseJSON { response in
guard let dict = response.result.value as? [String: AnyObject], let currentDate = dict["full date"] as? String else {
//handle error here if response fails to give you good data
completed()
return
}
self.date = currentDate
print(self.date)
print("xxx")
completed()
}
}

swift+tableview data is not populated when searchbar is active

When I load my table then activate the search, I can get the search data in my tableview. To make my app faster, I create a seperate view only for search. But I couldn't get my tableview populated with search data. I can see I get the data correctly with print(data), but my table is not populated.
class YazarTableViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {
var searchResults: [JSON]? = []
var searchController = UISearchController()
#IBOutlet weak var searchButton: UIBarButtonItem!
#IBAction func searchButtonTouched(sender: AnyObject) {
showSearchBar()
}
func showSearchBar() {
self.searchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.searchBar.delegate = self
controller.dimsBackgroundDuringPresentation = true
controller.searchBar.alpha = 0
navigationItem.setLeftBarButtonItem(nil, animated: true)
UIView.animateWithDuration(0.5, animations: {
controller.searchBar.alpha = 1
}, completion: { finished in
controller.searchBar.becomeFirstResponder()
})
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
}
}
func updateSearchResultsForSearchController(searchController: UISearchController)
{
self.searchResults?.removeAll(keepCapacity: false)
if (!searchController.searchBar.text!.isEmpty){
let parameters = ["q" : searchController.searchBar.text]
var searchURL = "http://apilink.com/" + String(parameters) + "/1"
searchURL = searchURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
Alamofire.request(.GET, searchURL, encoding: .JSON)
.responseJSON{ response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling GET on /posts/1")
print(response.result.error!)
return
}
if let value: AnyObject = response.result.value {
let post = JSON(value)
if let data = post[].arrayValue as [JSON]?{
self.searchResults = data
self.tableView.reloadData()
print(data)
}
}
}
}
}

unexpectedly found nil while unwrapping an Optional value for my UITextField

I'm having trouble passing the JSON values (I'm reading successfully) into my textfield on the next viewcontroller because of this unwrapping error, stating my text field is nil.
I'm very stuck. Here's my class that reads the JSON:
class DoOAuth
{
func doOAuthFitbit() -> String{
var name = ""
let oauthswift = OAuth1Swift(
consumerKey: "eabf603efe9e45168d057b60b03f8e94",
consumerSecret: "46b4dfa8c9d59666769e03f887d531a8",
requestTokenUrl: "https://api.fitbit.com/oauth/request_token",
authorizeUrl: "https://www.fitbit.com/oauth/authorize?display=touch",
accessTokenUrl: "https://api.fitbit.com/oauth/access_token")
oauthswift.authorizeWithCallbackURL( NSURL(string: "fitbit://oauth")!,
success:{
credential, response in
let vc: ViewController = ViewController()
let user: OAuthSwiftClient = OAuthSwiftClient(consumerKey: oauthswift.consumer_key, consumerSecret: oauthswift.consumer_secret, accessToken: credential.oauth_token, accessTokenSecret: credential.oauth_token_secret)
let object:[String : AnyObject] = ["oauth_token": credential.oauth_token, "oauth_token_secret" : credential.oauth_token_secret]
user.get("https://api.fitbit.com/1/user/-/profile.json", parameters: object,
success: {
(data: NSData, response: NSHTTPURLResponse) -> Void in
let jsonValues = JSON(data: data, options: NSJSONReadingOptions.AllowFragments, error: nil)
println(jsonValues)
/*public var dictionary: [Swift.String: JSON]?
{
switch self
{
case .Dictionary(let d):
var jsonObject: [Swift.String: JSON] = [:]
for(k,v) in d
{
jsonObject[k] = JSON.wrap(v)
}
return jsonObject
default:
return nil
}
}*/
for(key, subJson) in jsonValues
{
if let nm = subJson["fullName"].string
{
println("\(nm)")
name = nm
}
}
/*for(index: String, subJson: JSON) in jsonValues
{
let name = subJson.dictionary?["fullName"]?.string
println("\(name!)")
//vc.nm.text = name!
main.acceptJson(name!)
}*/
},
failure: {
(error:NSError!) -> Void in
println(error.localizedDescription)
println("error")
})
},
failure: {
(error:NSError!) -> Void in
println(error.localizedDescription)
})
return name
}
}
I call a function that is supposed to receive the JSON strings (acceptJson) located in the next view controller:
class mainMenu: UIViewController
{
var oauthfitbit: DoOAuth = DoOAuth()
var name = ""
//let vc: ViewController = ViewController()
#IBOutlet weak var lbl: UILabel!
#IBOutlet weak var nameField: UITextField!{
didSet{
nameField.text = name
}
}
override func viewWillAppear(animated: Bool)
{
//name = oauthfitbit.doOAuthFitbit()
//self.nameField.text = "Working"
//self.nameField.text = name
}
func acceptJson(info: String!)
{
println("\(info)")
self.nameField.text = info
//name = info
}
}
I get the excepting thrown on the setting nameField.text line stating nameField is nil. How do I get the textfield to store the JSON string?
And here's the initial View Controller:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var nm: UITextField!
//let main: mainMenu = mainMenu()
var name = ""
#IBAction func connectPressed(sender: UIButton)
{
var oauthFitbit: DoOAuth = DoOAuth()
name = oauthFitbit.doOAuthFitbit()
self.performSegueWithIdentifier("loginSuccess", sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "loginSuccess")
{
let controller = segue.destinationViewController as! mainMenu
controller.name = name
//vc.nameField.text = "Hello"
}
}
}
How did you create your textfield? Was it through Interface Builder? There have been plenty of times when I've run into these type of problems when using Interface Builder and IBOutlets.
The first step is to make sure your text field is connected to your view controller from the .xib file correctly. Delete the connection and reconnect by control (command?) dragging from IB to your view controller code.
If you're not using IB and still having problems, post the code where you create the textfield. You have to set your view controller as the text field delegate if you're creating it programmatically, I believe. It's been awhile since I've done it that way.
Let us know!
The easiest way to get the new view controller the value of nm is in prepareForSegue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "YourIdentifier" {
let controller = segue.destinationViewController as! mainMenu
controller.name = name
}
}
So, to get this to work, you will need to add a name instance variable (var name = "") to your first view controller, and change main.acceptJson(nm) to name = nm.
Once name is set in your first view controller, you can segue to the second view controller.
In the second view controller, you can change your text field outlet to this:
#IBOutlet weak var nameField: UITextField! {
didSet {
nameField.text = name
}
}
The didSet is a property observer. You can't set the nameField text field directly from the first view controller's prepareForSegue because the text field isn't set up yet when prepareForSegue is called in the first view controller. That's why you're storing it in an instance variable. Then, because of the didSet, your text field's text property will be set as soon as it comes into existence.
UPDATE:
The following is in a class of its own. Let's call that class DoOAuth (looks like that's what you called it):
class DoOAuth {
func doOAuthFitbit() -> String { // Now it's returning a string
var name = "" // Create local variable to return
let oauthswift = OAuth1Swift(
consumerKey: "eabf603efe9e45168d057b60b03f8e94",
consumerSecret: "46b4dfa8c9d59666769e03f887d531a8",
requestTokenUrl: "https://api.fitbit.com/oauth/request_token",
authorizeUrl: "https://www.fitbit.com/oauth/authorize?display=touch",
accessTokenUrl: "https://api.fitbit.com/oauth/access_token")
oauthswift.authorizeWithCallbackURL( NSURL(string: "fitbit://oauth")!,
success:{
credential, response in
//let vc: ViewController = ViewController() // Get rid of this
let user: OAuthSwiftClient = OAuthSwiftClient(consumerKey: oauthswift.consumer_key, consumerSecret: oauthswift.consumer_secret, accessToken: credential.oauth_token, accessTokenSecret: credential.oauth_token_secret)
let object:[String : AnyObject] = ["oauth_token": credential.oauth_token, "oauth_token_secret" : credential.oauth_token_secret]
user.get("https://api.fitbit.com/1/user/-/profile.json", parameters: object,
success: {
(data: NSData, response: NSHTTPURLResponse) -> Void in
let jsonValues = JSON(data: data, options: NSJSONReadingOptions.AllowFragments, error: nil)
println(jsonValues)
/*public var dictionary: [Swift.String: JSON]?
{
switch self
{
case .Dictionary(let d):
var jsonObject: [Swift.String: JSON] = [:]
for(k,v) in d
{
jsonObject[k] = JSON.wrap(v)
}
return jsonObject
default:
return nil
}
}*/
for(key, subJson) in jsonValues
{
if let nm = subJson["fullName"].string
{
println("\(nm)")
name = nm // Store 'nm' in local variable declared above
}
}
}
return name
} // end doOAuthFitbit()
} // end class
Now change your connectPressed() method in ViewController to this:
#IBAction func connectPressed(sender: UIButton)
{
var oauthFitbit: DoOAuth = DoOAuth()
name = oauthFitbit.doOAuthFitbit() // doOAuthFitbit() now returns a String
self.performSegueWithIdentifier("loginSuccess", sender: nil)
}
Now it should work.