Created
June 10, 2019 02:08
-
-
Save jkereako/d63dd8f1b65a473dc28e28e5c04c638f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import JavaScriptCore | |
import Foundation | |
let context = JSContext()! | |
import JavaScriptCore | |
@objc protocol MovieJSExports: JSExport { | |
var title: String { get set } | |
var price: String { get set } | |
var imageURL: String { get set } | |
static func createWith(title: String, price: String, imageURL: String) -> Movie | |
} | |
final class Movie: NSObject, MovieJSExports { | |
dynamic var title: String | |
dynamic var price: String | |
dynamic var imageURL: String | |
init(title: String, price: String, imageURL: String) { | |
self.title = title | |
self.price = price | |
self.imageURL = imageURL | |
} | |
class func createWith(title: String, price: String, imageURL: String) -> Movie { | |
return Movie(title: title, price: price, imageURL: imageURL) | |
} | |
} | |
context.setObject(Movie.self, forKeyedSubscript: "Movie" as NSString) | |
context.exceptionHandler = { context, exception in | |
print(exception!.toString()!) | |
} | |
let result = context.evaluateScript(#""" | |
class MovieService { | |
constructor() { | |
this._url = "https://itunes.apple.com/us/rss/topmovies/limit=50/json"; | |
} | |
get url() { | |
return this._url; | |
} | |
set url(url) { | |
this._url = url | |
} | |
fetchMovies() { | |
return new Promise(function(resolve, reject) { | |
var request = new XMLHttpRequest(); | |
request.open('GET', url, true); | |
request.responseType = "json"; | |
request.onload = function() { | |
if (request.status >= 400 || request.status <= 599) { | |
reject(Error(request.status)); | |
} | |
var movies = JSON.parse(request.response).map((attributes) => { | |
// Create a new Movie object | |
return { | |
"title": attributes['im:name']['label'], | |
"price": Number(attributes['im:price']['attributes']['amount']).toFixed(2), | |
"imageUrl": attributes['im:image'].reverse()[0]['label'] | |
}; | |
}); | |
resolve(movies); | |
}; | |
request.send(); | |
}); | |
} | |
} | |
"""#) | |
context.evaluateScript("var service = new MovieService();") | |
context.evaluateScript(#""" | |
service.fetchMovies().then(function(value) { | |
callback(value); | |
}); | |
"""# | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment