Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
for appID in appIDs {
let urlString = "https://itunes.apple.com/lookup?id=" + appID
if let
url = NSURL(string:urlString),
data = NSData(contentsOfURL: url),
json = NSJSONSerialization.JSONObjectWithData(
data, options: NSJSONReadingOptions(0),
error: nil) as? NSDictionary,
resultsList = json["results"] as? NSArray,
results = resultsList.firstObject as? NSDictionary,
name : AnyObject = results["trackName"],
price : AnyObject = results["formattedPrice"] {
println("\(name): \(price)")
}
}
func ShowPrices(productURLStrings: [String]) {
println("Today's prices")
for productURLString in productURLStrings {
var urlString = FetchQuery(productURLString)
if let json = JSON.fetchURLString(urlString),
dict = json.rawValue as? NSDictionary,
resultsList = dict["results"] as? NSArray,
results = resultsList.firstObject as? NSDictionary,
name = results["trackName"] as? NSString,
formattedPrice = results["formattedPrice"] as? NSString {
println("\(name): \(formattedPrice)")
}
}
println()
}
func CheckRatings(productURLStrings: [String]) {
println("Checking ratings")
for productURLString in productURLStrings {
var urlString = FetchQuery(productURLString)
if let json = JSON.fetchURLString(urlString),
dict = json.rawValue as? NSDictionary,
resultsList = dict["results"] as? NSArray,
results = resultsList.firstObject as? NSDictionary,
name = results["trackName"] as? NSString {
print("\(name): ")
if let averageUserRating = results["averageUserRating"] as? NSNumber {
println("\(averageUserRating) stars") // iBooks
} else if let trackContentRating = results["trackContentRating"] as? NSNumber {
println("\(trackContentRating) stars") // iOS, OS X
} else {
println("ratings not available")
}
}
}
println()
}
func ShowPrices(productURLStrings: [String]) {
println("Today's prices")
for productURLString in productURLStrings {
var urlString = FetchQuery(productURLString) // format URL
if let json = JSON.fetchURLString(urlString), // fetch JSON
dict = json.rawValue as? NSDictionary, // fetch dict
resultsList = dict["results"] as? NSArray, // fetch results array
results = resultsList.firstObject as? NSDictionary, // fetch info
name = results["trackName"] as? NSString, // fetch track name
formattedPrice = results["formattedPrice"] as? NSString { // fetch price
println("\(name): \(formattedPrice)")
}
}
println()
}
func CheckRatings(productURLStrings: [String]) {
println("Checking ratings")
for productURLString in productURLStrings {
var urlString = FetchQuery(productURLString) // format URL
if let json = JSON.fetchURLString(urlString), // fetch JSON
dict = json.rawValue as? NSDictionary, // fetch dict
resultsList = dict["results"] as? NSArray, // fetch results array
results = resultsList.firstObject as? NSDictionary, // fetch info
name = results["trackName"] as? NSString { // fetch track name
print("\(name): ")
// Rating keys vary by content type
if let averageUserRating = results["averageUserRating"] as? NSNumber {
println("\(averageUserRating) stars") // iBooks
} else if let trackContentRating = results["trackContentRating"] as? NSNumber {
println("\(trackContentRating) stars") // iOS, OS X
} else {
println("ratings not available")
}
}
}
println()
}
func ShowPrices(productURLStrings: [String])
{
println("Today's prices")
for productURLString in productURLStrings
{
var urlString = FetchQuery(productURLString) // format URL
if let json = JSON.fetchURLString(urlString), // fetch JSON
dict = json.rawValue as? NSDictionary, // fetch dict
resultsList = dict["results"] as? NSArray, // fetch results array
results = resultsList.firstObject as? NSDictionary, // fetch info
name = results["trackName"] as? NSString, // fetch track name
formattedPrice = results["formattedPrice"] as? NSString // fetch price
{
println("\(name): \(formattedPrice)")
}
}
println()
}
func CheckRatings(productURLStrings: [String])
{
println("Checking ratings")
for productURLString in productURLStrings
{
var urlString = FetchQuery(productURLString) // format URL
if let json = JSON.fetchURLString(urlString), // fetch JSON
dict = json.rawValue as? NSDictionary, // fetch dict
resultsList = dict["results"] as? NSArray, // fetch results array
results = resultsList.firstObject as? NSDictionary, // fetch info
name = results["trackName"] as? NSString // fetch track name
{
print("\(name): ")
// Rating keys vary by content type
if let averageUserRating = results["averageUserRating"] as? NSNumber
{
println("\(averageUserRating) stars") // iBooks
}
else if let trackContentRating = results["trackContentRating"] as? NSNumber
{
println("\(trackContentRating) stars") // iOS, OS X
}
else
{
println("ratings not available")
}
}
}
println()
}
func ShowPrices(productURLStrings: [String])
{
println("Today's prices")
for productURLString in productURLStrings {
var urlString = FetchQuery(productURLString)
if let json = JSON.fetchURLString(urlString) {
// Name
if let name = json.valueForKeypath(
["results", 0, "trackName"]) as? String {
print("\(name): ") }
// Formatted Price
if let formattedPrice = json.valueForKeypath(
["results", 0, "formattedPrice"]) as? String {
println("\(formattedPrice)") }
}
}
println()
}
func CheckRatings(productURLStrings: [String])
{
println("Checking ratings")
for productURLString in productURLStrings {
var urlString = FetchQuery(productURLString)
if let json = JSON.fetchURLString(urlString) {
// Name
if let name = json.valueForKeypath(
["results", 0, "trackName"]) as? String {
print("\(name): ") }
// Rating keys vary by content type
if let averageUserRating = json.valueForKeypath(
["results", 0, "averageUserRating"]) as? NSNumber {
println("\(averageUserRating) stars") // iBooks
}
else if let trackContentRating = json.valueForKeypath(
["results", 0, "trackContentRating"]) as? NSNumber {
println("\(trackContentRating) stars") // iOS, OS X
}
else {
println("ratings not available")
}
}
}
println()
}
extension Array {
func atIndex(index: UInt) -> Element? {
return Int(index) < count ? self[Int(index)] : nil
}
}
public enum JSON : Printable {
case NullValue
case NumberValue(Double)
case StringValue(String)
case ArrayValue([NSObject])
case DictionaryValue([NSObject:AnyObject])
public var rawValue: AnyObject? {
switch self {
case .NullValue: return nil
case .NumberValue (let d): return d
case .StringValue (let s): return s
case .ArrayValue (let a): return a
case .DictionaryValue (let d): return d
}
}
public var description : String {
switch self {
case .NullValue: return "Null"
case .NumberValue (let d): return "Number<\(d)>"
case .StringValue (let s): return "String<\(s)>"
case .ArrayValue (let a): return "Array<\(a)>"
case .DictionaryValue (let d): return "Dict<\(d)>"
}
}
// Fallback initializer is null
public init() {self = .NullValue}
// Initialize with type
public init?<T>(_ t : T){
switch t {
case let value as NSNull: self = .NullValue
case let value as Double: self = .NumberValue(value)
case let value as String: self = .StringValue(value)
case let value as [NSObject]: self = .ArrayValue(value)
case let value as [NSObject:AnyObject]: self = .DictionaryValue(value)
default: return nil
}
}
// Initializer entry point for optionals
public init?<T>(_ t : T?){
if let t = t {self.init(t)} else {self.init()}
}
public static func fetchURLString(urlString : String) -> JSON? {
if let
url = NSURL(string:urlString),
data = NSData(contentsOfURL: url),
jsonRep : AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil) {
return JSON(jsonRep)
}
return nil
}
public func valueForKey(index : UInt) -> JSON? {
switch self {
case .ArrayValue(let array): return JSON(array.atIndex(index))
default: return nil
}
}
public func valueForKey(string: String) -> JSON? {
switch self {
case .DictionaryValue(let dict): return JSON(dict[string])
default: return nil
}
}
public func jsonForKeypath(keypath: ArraySlice<AnyObject>) -> JSON? {
if isEmpty(keypath) {return self}
switch keypath.first {
case let stringValue as String: return valueForKey(stringValue)?.jsonForKeypath(dropFirst(keypath))
case let uintValue as UInt: return valueForKey(uintValue)?.jsonForKeypath(dropFirst(keypath))
default: return nil
}
}
public func valueForKeypath(keypath : ArraySlice<AnyObject>) -> AnyObject? {
return jsonForKeypath(keypath)?.rawValue
}
}
@jtbandes

This comment has been minimized.

Copy link

@jtbandes jtbandes commented May 31, 2015

How about a helper function?

func firstResult(productURLString: String) -> NSDictionary?
{
    if let json = JSON.fetchURLString(FetchQuery(productURLString)),
        dict = json.rawValue as? NSDictionary,
        resultsList = dict["results"] as? NSArray,
        result = resultsList.firstObject as? NSDictionary
    {
        return results
    }
    return nil
}

func ShowPrices(productURLStrings: [String])
{
    println("Today's prices")
    for productURLString in productURLStrings
    {
        if let result = firstResult(productURLString),
            name = result["trackName"] as? NSString,
            formattedPrice = result["formattedPrice"] as? NSString
        {
                println("\(name): \(formattedPrice)")
        }
    }
    println()
}

func CheckRatings(productURLStrings: [String])
{
    println("Checking ratings")
    for productURLString in productURLStrings
    {
        if let result = firstResult(productURLString),
            name = result["trackName"] as? NSString
        {
            print("\(name): ")

            // Rating keys vary by content type
            if let rating = results["averageUserRating"] as? NSNumber ?? result["trackContentRating"] as? NSNumber
            {
                println("\(rating) stars")
            }
            else
            {
                println("ratings not available")
            }
        }
    }
    println()
}
@ilyannn

This comment has been minimized.

Copy link

@ilyannn ilyannn commented May 31, 2015

Great code challenge!

After some investment into helper functions and operators, we can do things like this:

// MARK: Main functions
func ShowPrices(productURLStrings: [String]) {
    println("Today's prices")

    productURLStrings 
        ➜ FetchQueryURL  
        ➜ NSURL.fetchJSON      
        ➜ usingFirst(JSON.extractPrice) 
        ➜ { "\($0.name): \($0.formattedPrice)" }
        ➜ println

    println()
}

func CheckRatings(productURLStrings: [String]) {
    println("Checking ratings")

    productURLStrings
        ➜ FetchQueryURL 
        ➜ NSURL.fetchJSON 
        ➜ usingFirst(JSON.extractRating)    
        ➜ { "\($0.name): \($0.starDescription)" } 
        ➜ println

    println()
}

See this gist.

@alskipp

This comment has been minimized.

Copy link

@alskipp alskipp commented Jun 1, 2015

Here's an example of how I'd approach the problem. Full gist can be found here

let json = JSONFromFile("example")

let product = json
  >>- toJSONArray("results")
  >>- first
  >>- productFromJSON

product?.name                 // Yelp
product?.formattedPrice       // Free
product?.averageUserRating    // 4
product?.trackContentRating   // 12+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.