How to display JSON data into UILabel in Swift 3.0 ?
I have these three (3) UILabel named login,email and pw
Right now i managed to display the JSON in output section but i don't know how to display that JSON data into UILabel.
Here's my JSON data
[
{"login":"ID001","pw":"123","email":"first#p.com"},
{"login":"ID002","pw":"456","email":"second#p.com"}
]
And my viewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet var login: UILabel!
#IBOutlet var email: UILabel!
#IBOutlet var pw: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://localhost/get.php")
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 AnyObject
print(myJSON)
}
catch {
}
}
}
}
task.resume()
}
}
Thanks.
You can decode your json data like that.
do {
if let myJSON = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String:Any]] {
print(json)
for jsonDictionary in myJSON {
print(jsonDictionary["login"]!)
print(jsonDictionary["pw"]!)
print(jsonDictionary["email"]!)
}
}
} catch {
print("Something went wrong")
}
Related
I am a total beginner with programming and Swift. One of the features my app should have is a label of the current temperature in New York City. The problem is I don't know if I am on the right path with my code. I tried things from many videos and articles but nothing seems to work. I am sure the answer is very easy. Thanks for any help!
I use the darksky api. This is my current code.
import UIKit
struct MyGitHub: Codable {
let temperature: Int
private enum CodingKeys: String, CodingKey {
case temperature
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
guard let gitUrl = URL(string: "here is my darksky api") else { return }
URLSession.shared.dataTask(with: gitUrl) { (data, response, error) in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
let gitData = try decoder.decode(MyGitHub.self, from: data)
print (gitData.temperature)
} catch let err {
print ("Err", err)
}
} .resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You need an umbrella struct for the root object and the value for key temperature is Double, not Int
struct Root: Decodable {
let currently : MyGitHub
}
struct MyGitHub: Decodable {
let temperature: Double
}
...
let gitData = try decoder.decode(Root.self, from: data)
print(gitData.currently.temperature)
You can try this
Alamofire.request(urlStr, method: .get, parameters:nil, encoding: JSONEncoding.default).responseJSON { response in
if let json = response.result.value as? [String:Any] {
if let main = json["currently"] as? [String:Any] {
if let temp = main["temperature"] as? NSNumber
{
// set lbl here
print(temp)
}
}
}
}
OR
struct Currently : Codable {
var currently:InnerItem
}
struct InnerItem : Codable {
var temperature:Double
}
with
guard let gitUrl = URL(string:urlStr) else { return }
URLSession.shared.dataTask(with: gitUrl) { (data, response, error) in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
let gitData = try decoder.decode(Currently.self, from: data)
print ("sdhjsdjhjhdshjshjsjhddhsj" , gitData.currently.temperature)
} catch let err {
print ("Err", err)
}
} .resume()
This is my JSON data
{
"Number":"ID001",
"Password":"1111",
"Email":"email#gmail.com"
}
Currently i'm using SwiftyJSON to print specific JSON output in X Code. So far i managed to print email value specifically. But i'm not sure how to display email value in UILabel emailLbl.
The code as below.
import UIKit
import SwiftyJSON
class ViewController: UIViewController {
#IBOutlet var emailLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://localhost/get.php")
let task = URLSession.shared.dataTask(with: url!) {
(data, response, error) in
if error != nil {
print("Error")
}
else {
guard let data = data else {
print("data was nill ?")
return
}
let json = JSON(data: data)
print(json["email"].string!)
}
}
task.resume()
}
}
Does Anyone have any idea how ?
Thanks.
Try this:
let json = JSON(data: data)
print(json["email"].string!)
self.emailLbl.text = json["email"].string!
My code is this
import UIKit
import Alamofire
class ViewController: UIViewController {
var young = "https://jsonplaceholder.typicode.com/posts"
override func viewDidLoad() {
super.viewDidLoad()
callAlamo(url: young)
}
func callAlamo(url: String){
Alamofire.request(url).responseJSON { (response) in
let responseJSON = response.data
if responseJSON == nil{
print("response is empty")
}else{
print("Jon is \(responseJSON)")
self.parseJson(JSONData: responseJSON!)
}
}
}
func parseJson(JSONData: Data){
do{
let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers)
for i in 0..<(readableJSON as AnyObject).count{
print(readableJSON[i] as String)
}
}catch{
print(error)
}
}
}
I need each array element inside this Json.
Try to use below code:
Alamofire.request(url).responseJSON { (response) in
switch response.result {
case .success(let value) :
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value as! [String:AnyObject]!{
print("JSON: ",JSON)
}
case .failure(let encodingError):
completionHandler(APIResponse.init(status: "failure", response: nil, result:nil))
}
}
When using the responseJSON handler, the JSON data has already been parsed internally by JSONSerialization. You do NOT want to try to parse it again, otherwise you're parsing the server's response data twice which is really bad for performance. All you need to do is the following:
Alamofire.request(url).responseJSON { response in
if let json = response.result.value {
print("Parsed JSON: \(json)")
// Now you can cast `json` to a Dictionary or Array
}
}
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.
I'm new to coding and have a (hopefully easy) question.
I am trying to display JSON data as a label using swift. I'm not getting any errors but nothing is showing up using the following code:
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, ErrorType) -> Void in
if let urlContent = data {
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers)
print(jsonResult)
let text = jsonResult as? String
self.textLabel.text = text
} catch {
print("JSON serialization failed")
}
}
}
task.resume()
Thanks!
Just update your label into main thread this way:
dispatch_async(dispatch_get_main_queue()) {
self.textLabel.text = text
}
UPDATE:
You can use SwiftyJSON for that.
And below is your working code with that library:
import UIKit
class ViewController: UIViewController {
var dict = NSDictionary()
#IBOutlet weak var authorLbl: UILabel!
#IBOutlet weak var quoteLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "http://api.theysaidso.com/qod.json"
if let url = NSURL(string: urlString) {
if let data = try? NSData(contentsOfURL: url, options: []) {
let json = JSON(data: data)
print(json)
let auther = json["contents"]["quotes"][0]["author"].stringValue
let quote = json["contents"]["quotes"][0]["quote"].stringValue
authorLbl.text = auther
quoteLbl.text = quote
}
}
}
}