swiftyJSON parsing json from NSURL - json

i would ask a little help..
I have a function which try to get json data from a url. I am using SwiftyJSON.
this is my function:
func getDataFromUpc(Code: String) {
print("called getdata")
let urlString = "http://api.upcdatabase.org/json/mykey/" + Code
print(urlString)
let url = NSURL(string: urlString)
let data = NSData(contentsOfURL: url!)
let json = JSON(data!)
print(json)
print(json["description"])
self.alert(json["description"].stringValue)
}
when i try to print the json object on the console i can see this:
unknown
and when i try to print json["description"] it's nil.
If i try to call my url with my browser it's works and i get back the json response.
Could anybody please help me what am I doing wrong?
Thank you very much!

swiftyJSON don´t works with URL´s , swiftJSON works perfectly with local data
this is a tutorial that you can see to understand more the swiftJSON
https://www.youtube.com/watch?v=_NfijT6mt6A
to parse the JSON from the web you need to do that...
https://www.youtube.com/watch?v=r-LZs0De7_U

Related

How can I get the JSON response in dictionary format in swift3?

I'm working on JSON serialization like below code:
let jsonData: Data? = try? JSONSerialization.data(withJSONObject: abc, options: .prettyPrinted)
let parsedDict = String(data: jsonData!, encoding: String.Encoding.utf8)
print(" parse Dict Value \(parsedDict!)")
abc data is:
{
"ActedTime" = "2017-09-19 12:04:12",
"EventDate" = "2017-10-06 07:03:29"
}
After completion of serialization, the response value is:
"{\n \"ActedTime\" : \"2017-09-19 12:04:12\",\n \"EventDate\" : \"2017-10-06 07:03:29\”}”
I printed the parsedDict like below:
{
"ActedTime" : "2017-09-19 12:04:12",
"EventDate" : "2017-10-06 07:03:29"
}
The stored data seems like string format, but data is printed like dictionary.
How can I get dictionary format for sent the parameters to another API like dictionary format.
Please help me,
Thanks in Advance.
Omit .prettyPrinted, the server doesn't care anyway.
let jsonData = try? JSONSerialization.data(withJSONObject: abc)
And if the object is supposed to be a dictionary, why do you serialize it at all?
However if the data is supposed to be passed in a POST request as httpBody pass jsonData rather than parsedDict.

Swift Console Output to Text Label

I am trying to take console output from a json request and post it as a text label for the user. I can't seem to get it to work. Any advice? Thanks! It prints fine in the console, but won't work for the "self.resultLabel.text = json"
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
print(json)
dispatch_async(dispatch_get_main_queue(),{
self.myActivityIndicator.stopAnimating()
self.myImageView.image = nil;
self.resultLabel.text = json
func loadSites(){
//trying to get the post to show up in the place of the invisible label
}
});
}catch {
print(error)
}
I am not sure why exactly you want to show raw json to users in UILabel but you should convert json to a string if you want to assign it to UILabel's text property.
There is a description method, which is always used in Objective-C whenever you print an NSObject subclass via NSLog.
This method is also available in Swift:
self.resultLabel.text = (json as AnyObject).description

Read data from a html page in Swift

I want to code an app which shows you the data of a specific HTML-Page.
How can read the text e.g. in a div and turn that text into a String? How can I search something on that page or look in the row of a table?
You need mind what is the step you need to complete this task.
First need load html page data
After find what do you need with parser.
In the first step I found this code
let url = NSURL(string: "http://www.stackoverflow.com")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
task.resume()
Example from this link How to make an HTTP request in Swift?
Look this example, you do a request and return a data, this data need be String. After received data you need parse to findo what do you want.
Second step you need tools to execute, the simple way is do with string methods like slipt. If you need something more smart I recommend Regular Expression
Simple example for split (swift 1.2)
var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
example (swift 2.0)
let fullName = "First Last"
let fullNameArr = split(fullName.characters){$0 == " "}.map(String.init)
fullNameArr[0] // First
fullNameArr[1] // Last
Examples from Swift: Split a String into an array
This link is good about Regular Expression, mind it is a powerfull tool to parse, with this you can search anything in your html.
NSRegularExpression Tutorial: Getting Started
I hope helped you with this explanation.
Updated syntax (swift 5) with a few modifications to get html data:
let url = NSURL(string: "https://www.stackoverflow.com")
let task = URLSession.shared.dataTask(with: url! as URL) {(data, response, error) in
if data != nil { // otherwise will crash for if url is empty
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!
print("url data:",dataString)
} else {print("url data not found")}
}
task.resume()

HTTPTask response into Swifty for JSON serialization

I'm using HTTPTask to load data from openweathermap.org. Which is working fine. I'm having trouble converting the data to JSON. I'd like to use SwiftyJSON but, I can't quite figure out how to bridge the two.
HTTPTask has a JSON Serializer, which I got working, but I rather use Swifty, it's seems easier to work with.
Here's what I have so far. This loads the weather from openweathermap.org. I'm not sure how to pass the response into Swifty.
var request = HTTPTask()
request.requestSerializer = JSONRequestSerializer()
request.responseSerializer = JSONResponseSerializer()
request.GET(openWeatherURL, parameters: ["q":"San Francisco", "APPID":openWeatherAPIKey], success: {(response: HTTPResponse) in
if let dict = response.responseObject as? Dictionary<String, AnyObject> {
println("Response: \(response)")
println("Dictionary: \(dict)")
let description = dict["weather"]["description"]
println(description)
}
}, failure: {(error: NSError, repsonse: HTTPResponse?) in
println("error \(error)")
})
SwiftyJSON is quite happy to take a variety of objects, including Dictionary?, so just go for it!
let dict = JSON(response.responseObject)

How do I access the data when I am using NSURLSession?

I am new to iOS development. I am using Swift and I have very little experience with Objective-C, so some of the other possibly related answers are tricky to understand. I am trying to understand how to use NSURLSession to get some data from a JSON file on the Web. I found some useful information about getting a file from a URL, but like this other StackOverflow user (NSURLSessionDataTask dataTaskWithURL completion handler not getting called), I heard that NSURLConnection was not the current way to get data, so I'm trying to use NSURLSession.
When I am getting my JSON from the bundle, I am using this extension to
Dictionary (I am pretty sure I got this code from a tutorial):
static func loadJSONFromBundle(filename: String) -> Dictionary<String, AnyObject>? {
let path = NSBundle.mainBundle().pathForResource(filename, ofType: ".json")
if !path {
println("Could not find level file: \(filename)")
return nil
}
var error: NSError?
let data: NSData? = NSData(contentsOfFile: path, options: NSDataReadingOptions(),
error: &error)
if !data {
println("Could not load level file: \(filename), error: \(error!)")
return nil
}
let dictionary: AnyObject! = NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions(), error: &error)
if !dictionary {
println("Level file '\(filename)' is not valid JSON: \(error!)")
return nil
}
return dictionary as? Dictionary<String, AnyObject>
}
I'd like to do something similar for getting a dictionary from a JSON file that is on the web because I don't anticipate wanting to include all of my JSON files in the bundle. So far, I have this:
static func loadJSONFromWeb(urlstring: String) -> Dictionary<String, AnyObject>? {
let url = NSURL(string: urlstring)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config, delegate: nil, delegateQueue: NSOperationQueue())
var error: NSError?
//I think I am using the completionHandler incorrectly. I'd like to access the data from the download
let task = session.downloadTaskWithRequest(NSURLRequest(URL: url), {(url, response, error) in println("The response is: \(response)")
})
task.resume()
//Isn't this contentsOfURL thing supposed to go with the connection stuff rather than the session stuff?
//How can I do this with a session? How can I create and use a completionHandler? This way seems clunky.
let data: NSData? = NSData(contentsOfURL: url)
if !data {
println("Could not load data from file: \(url), error: \(error!)")
return nil
}
println("The data is: \(data)")
let dictionary: AnyObject! = NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions(), error: &error)
if !dictionary {
println("The file at '\(url)' is not valid JSON, error: \(error!)")
return nil
}
return dictionary as? Dictionary<String, AnyObject>
}
I think that my actual question that most needs answering is this: Where
is the data? I don't think I am using sessions and tasks correctly. I feel like I'm
starting a session to connect to a specific URL and using resume() to
start the download task I want to make happen, but I don't know how to
get the data from that JSON file.
If I need to use a completionHandler and a request in a way similar to what I found here:
(popViewControllerAnimated work slow inside NSURLSessionDataTask) can someone please explain how the 'data' in the completionHandler relates to the data in the fie I am trying to read/download? I am a bit baffled by the completionHandler and how to use it properly.
I looked at the documentation for NSData as well, but I didn't see anything that helped me understand how to get data from my session (or how to initialize an instance of NSData given my session). As far as I can tell form the documentation for NSURLDownloadTask, the task itself is not how I can access the data. It looks like the data comes from the session and task through the completionHandler.
EDIT:
I also looked at the documentation for NSURLSessionDownloadDelegate, but I could really use an example in Swift with some explanation about how to use the delegate. This led me to the URL Loading System Programming Guide. I'm guessing the benefits of using a session must be huge if the documentation is this complicated. I'm going to keep looking for more information on the URL Loading System.
I found this answer helpful (but I'm so new I can't upvote anything yet): https://stackoverflow.com/a/22177659/3842582 It helped me see that I am probably going to need to learn to use a delegate.
I also looked at the URL Loading System Programming Guide. I think what I really need is help with a completionHandler. How can I get my data? Or, am I already doing it correctly using NSData(contentsOfURL: url) (because I don't think I am).
Thank you in advance for any help you can offer!
First, let data: NSData? = NSData(contentsOfURL: url) will return your JSON synchronously. Did you try that and get this working simply? That way you can get started with the rest of your processing while figuring out NSURLSession.
If you're going to use NSURLSession, or a lot of other things in iOS, you need to learn delegates. Fortunately, they're easy. In terms of syntax you just add it to your class declaration like you were inheriting from it. What that does is say that you are going to implement at least the required functions for the delegate. These are callback functions which are generally pretty well documented. It is quite straightforward once you understand it.
If this is not a "heavyweight" project that really needs NSURLSession, you should look at this Swift library. Besides being a really nice way to deal with JSON there is a synchronous call to directly load the JSON from a url. https://github.com/dankogai/swift-json/
Why is NSURLConnection not the correct way to get data? You just should be careful with synchronous requests. Here is an example of how to get data from an url.
func synchronousExampleRequest() -> NSDictionary {
//creating the request
let url: NSURL! = NSURL(string: "http://exampledomain/apiexample.json")
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
var error: NSError?
var response: NSURLResponse?
let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
error = nil
let resultDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
return resultDictionary
}