Use Post request response string in another method Swift - ios

I am trying to use response of the post request in prepareForSegue function. i want to assign response value to destination viewController property. i can not do that because when i assign it in side closure brackets, does not assign before view the new window. because inside the closure code read, after view the new window.
as well as i try to assign saveInvoice function assign to a variable and use within prepareForSegue function. but that variable is NSUrlSessionDataTask type, so i could not use it further.
bellow i have mentioned my code segment
calling function
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let previewVC :PreviewViewController = segue.destinationViewController as! PreviewViewController
previewVC.invoiceSummary = "test hash key"
let invoiceSave = saveInvoice({ hash_key in
print(hash_key)
let test = hash_key
if test != ""
{
print("Success")
}
previewVC.sendersName = "sender view controller name"
})
print(invoiceSave)
}
This is the function which handdle the post request
func saveInvoice(completionHandler: (NSString) -> Void) -> NSURLSessionDataTask
{
let invoiceSummary = "Sample invoice summary"
let invoiceDate = "2015-11-20"
let invoiceConnectionID = "647193"
//let json = ["summary": invoiceSummary, "date": invoiceDate, "business_id": invoiceConnectionID]
let json = NSMutableDictionary()
json.setValue(invoiceSummary, forKey: "summary")
json.setValue(invoiceDate, forKey: "2015-11-20")
json.setValue(invoiceConnectionID, forKey: "business_id")
let data = try? NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions(rawValue: 0));
let request = NSMutableURLRequest(URL: NSURL(string: "https://livetest.somedomain.com/api/invs?auth_token=jmkm6ijijejf23kmkdd")!)
request.HTTPMethod = "POST"
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
request.HTTPBody = data
var outer = ""
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
let responceJSon = JSON(data: data!)
//let text = self.passJson(responceJSon)
let invoice = responceJSon["invoice"]
let hash_key = invoice["hash_key"].stringValue
let statement_number = invoice["statement_no"].stringValue
let statement_summary = invoice["summary"].stringValue
let statement_date = invoice["date"].stringValue
let obj = ["hash_key": hash_key, "statement_no": statement_number, "summary": statement_summary, "date": statement_date]
self.invObject.append(obj)
//self.invObject.append(text as! [String : String])
outer = self.invObject[0]["statement_no"]!
print(outer)
if let hash_key = invoice["hash_key"].string{
completionHandler(hash_key)
return
}
}
task.resume()
return task
}

First of all the saveInvoice executes asynchronously so you won't have the value when the next controller loads but a while after.
To save the variable you need to do that inside the completion block. I guess it's the hash_key that is of interest here?
so you would instead do something like this
saveInvoice({ hash_key in
previewVC.hash_key = hash_key
previewVC.sendersName = "sender view controller name"
})
However, as mentioned above this executes asynchronously so I rather think it would be better to start the save and then execute the segue programatically when the completion handler is called from within saveInvoice
saveInvoice({ hash_key in
savedHashKey = hash_key
self.performSegueWithIdentifier(segueName, sender: self)
})
and then in prepareForSegue
let savedHashKey:String? = nil
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let previewVC :PreviewViewController = segue.destinationViewController as! PreviewViewController
previewVC.invoiceSummary = savedHashKey
savedHashKey = nil
}

Related

Passing JSON Response From HTTP Request to Another ViewController in Swift 3

I'm new to iOS and was hoping someone would be willing to help me out with an issue I'm having
Say I have 2 Views in my storyboard:
- View1: Has 1 text box
- View2: Has 1 Label
Each being respectively controlled by a ViewControllers:
- FirstViewController
- SecondViewController
My app would send the text of the textbox in View1 as an HTTP (POST) request to an API, and would display on View2 the result which is sent back in JSON format.
My approach is to use the prepare(for segue:,Sender:), however I am having a hard time returning the JSON response from Task() in order to send it to SecondViewController via a Segue.
class ResultViewController: UIViewController {
#IBOutlet var text_input: UITextField!
Let api_url = (the api url)
func makeRequest(voucher_number:String, redemption_code:String){
let json: [String: Any] = [
"input" : text_input.text
]
let request_json = try? JSONSerialization.data(withJSONObject: json)
let url:URL = URL(string: api_url)!
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
request.httpBody = request_json
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data!, options: [])
}
catch
{
}
guard let server_response = json as? [String: Any] else
{
return
}
//This is where I think the return should take place
//but can't figure out how
})
task.resume()
}
}
I know I would need to modify my func declaration by adding the return syntax, but I can't figure out how to return data in the first place :P so I skipped this part for the time being.
I would then do the following to send the response to SecondViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "firstSegue" {
if let resultViewController = segue.destination as? SecondViewController {
if (text_input.text != nil && redemption_code.text != nil) {
if let json_response = makeRequest() {
SecondViewController.request_result = json_response
}
// request_result is the variable in
// SecondViewController that will store the data
// being passed via the segue.
}
}
}
}
I know my code may not be the best practice for what I'm trying to achieve. And I'm open to suggestions to tackle a different approach, as long as it's not too advanced for me.
Cheers
Notifications are a good way to forward JSON data out of completion handler blocks, like:
NotificationCenter.default.post(name: Notification.Name(rawValue:"JSON_RESPONSE_RECEIVED"), object: nil, userInfo: server_response)
Register and handle the notification in FirstViewController:
NotificationCenter.default.addObserver(self, selector: #selector(FirstViewController.json_Response_Received(_:)), name:NSNotification.Name(rawValue: "JSON_RESPONSE_RECEIVED"), object: nil)
(in viewDidLoad()) and:
func json_Response_Received(_ notification:Notification) {
responseDictionary = (notification as NSNotification).userInfo as! [String:AnyObject];
self.performSegue(withIdentifier: "SegueToSecondController", sender: self)
}
Then you can pass responseDictionary to SecondViewController in:
override func prepare(for segue:UIStoryboardSegue, sender:Any?) {
if (segue.identifier == "SegueToSecondController") {
secondViewController = segue.destinationViewController as! SecondViewController
secondViewController.response = responseDictionary
}
}

Can't go from a view to another after doing some instructions

I have this implementation in a part of my app:
Why when I click on "cerca per ISBN" button it goes to the tableView without doing the instructions that I have written?
This is the code of the "cerca per ISBN" button that I click:
#IBAction func ISBNButtonClick(_ sender: Any) {
let libro = Libro.text! as String
if Libro.text!.isEmpty {
//Alert per segnalare i campi mancanti, oltre a caselle rosse
var myAlert = UIAlertController(title:"Attenzione\n", message:"Inserire il codice ISBN", preferredStyle:UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default){ action in }
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
// placeholder rosso se la text è vuota
Libro.attributedPlaceholder = NSAttributedString(string:"Digita qui...", attributes: [NSForegroundColorAttributeName: UIColor.red])
//se tutti i campi obbligatori sono stati inseriti, proseguo ad altri controlli
}else{
if(isNumeric(string: libro)){
if((libro.characters.count) < 13 || (libro.characters.count) > 13){
//Alert per segnalare l'ISBN più corto di 13 numeri
var myAlert = UIAlertController(title:"Attenzione\n", message:"L'ISBN deve essere di 13 cifre", preferredStyle:UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default){ action in }
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}else{
//inviare dati al server
let myUrl = NSURL(string:"http://chuadiv.ddns.net/easytoschool/fetch_book_detailed.php");
let request = NSMutableURLRequest(url:myUrl as! URL);
request.httpMethod = "POST";
let postString = "name=\(libro)&mail=\(UserDefaults.standard.object(forKey: "userEmail") as? String)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil{
print("error=\(error)")
return
}
var err: NSError?
do{
var json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray
if let parseJSON: NSArray = json{
for index in 0...parseJSON.count-1 {
print("ciao")
let libro = parseJSON[index] as! [String:Any]
print("\n\n",index,":\n")
let book = resultCell.init(bookId: libro["id"] as! String,bookName: libro["name"] as! String,bookAuthor: libro["author"] as! String,bookSchool: libro["school"] as! String,bookPrice: libro["price"] as! String,bookStatus: libro["status"] as! String,bookISBN: libro["isbn"] as! String,bookType: libro["type"] as! String,bookIdSeller: libro["idSeller"] as! String,bookNameSeller: libro["nameSeller"] as! String,bookSurnameSeller: libro["surnameSeller"] as! String)
book.printBook();
HomeViewController.booksArray.append(book)
}
}
}catch{
print("error=\(error)")
return
}
}
task.resume();
performSegue(withIdentifier: "homeToListBook", sender: self)
}
}else{
var myAlert = UIAlertController(title:"Attenzione\n", message:"Inserire solo numeri per la ricerca attraverso codice ISBN", preferredStyle:UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default){ action in }
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}
}
}
I want that when I press the button it sets my array and after it goes to the tableView, but I can't
The issue is that completion block of dataTask will call async so it will call later and you are currently performing segue outside the completion block of it. So what you need to do is call performSegue inside the completion block of dataTask also on Main thread. Also use URL and URLRequest instead of NSURL and NS(Mutable)URLRequest
let myUrl = URL(string:"http://chuadiv.ddns.net/easytoschool/fetch_book_detailed.php")
let request = URLRequest(url:myUrl!)
request.httpMethod = "POST";
let postString = "name=\(libro)&mail=\(UserDefaults.standard.string(forKey: "userEmail")!)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil{
print("error=\(error)")
return
}
var err: NSError?
do{
var json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [[String:Any]]
if let parseJSON = json {
for libro in in parseJSON {
let book = resultCell.init(bookId: libro["id"] as! String,bookName: libro["name"] as! String,bookAuthor: libro["author"] as! String,bookSchool: libro["school"] as! String,bookPrice: libro["price"] as! String,bookStatus: libro["status"] as! String,bookISBN: libro["isbn"] as! String,bookType: libro["type"] as! String,bookIdSeller: libro["idSeller"] as! String,bookNameSeller: libro["nameSeller"] as! String,bookSurnameSeller: libro["surnameSeller"] as! String)
book.printBook();
HomeViewController.booksArray.append(book)
}
//Perform segue now
DispatchQueue.main.async {
performSegue(withIdentifier: "homeToListBook", sender: self)
}
}
}catch{
print("error=\(error)")
return
}
}
task.resume()
Note: In Swift use Swift native type array and dictionary instead of NSArray and NSDictionary.
you are appending items to an array of another instance, or even to some static var instead of passing it
what you should do is create class of Book with all properties
class Book {
let id: String
init(data: [String:Any]) {
self.id = data["id"] as? String ?? "" //or some other error handling
}
}
then create an array of books inside current UIViewController
var books: [Book] = []
then do something like
let book = Book(data: libro)
books.append(book)
to pass data you should create an array of books inside destination controller (HomeViewController)
set its DataSource and Delegate functions to create UITableViewCells using this array
and pass data like
override func prepare(for segue: UIStoryboardSegue, sender _: Any?) {
if segue.identifier == "homeToListBook" {
if let destinationVC = segue.destination as? HomeViewController {
destinationVC.books = self.books
}
}
}
EDIT:
and as Nirav D mentioned, segue should be called in main thread after data has been parsed, did not notice this

Populating UIView with results of NSURL

I am using an API that returns JSON which is parsed into a String. I want to then use this string as a label on another view controller. I tried using completion blocks but I can't get it to work, it continuously returns "Fatal error: expected optional returned nil" but I can't figure out where. I'm assuming it has something to do with asynchronous calls not allowing the popup class to populate with the String that the API hasn't returned yet.
func summarizeArticle(finished: () -> Void) {
let formatText = (searchText.text?.replacingOccurrences(of: " ", with: "_"))!
articleNameFormatted = ("https://en.wikipedia.org/wiki/" + formatText)
let request : NSMutableURLRequest = NSMutableURLRequest()
request.url = NSURL(string: urlString + articleNameFormatted) as URL!
request.httpMethod = "POST"
let url = request.url
URLSession.shared.dataTask(with:url!) { (data, response, error) in
if error != nil {
print(error!)
} else {
do {
let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
articleSummary = parsedData["sm_api_content"] as! String
print(articleSummary)
} catch let error as NSError {
print(error)
}
}
}.resume()
finished()
}
#IBAction func summarizeButtonPressed(_ sender: Any) {
self.view.endEditing(true)
summarizeArticle{
let popupVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "sbPopupVC") as! PopupViewController
popupVC.view.frame = self.view.frame
self.addChildViewController(popupVC)
self.view.addSubview(popupVC.view)
popupVC.didMove(toParentViewController: self)
}
}
The second view controller then uses this function which is supposed to grab the text from a global variable set by the previous functions:
override func viewDidLoad() {
super.viewDidLoad()
popupView.layer.cornerRadius = 10.0
popupView.clipsToBounds = true
summaryText.text = articleSummary
view.backgroundColor = UIColor.black.withAlphaComponent(0.0)
self.showAnimation()
}
Instead of making articleSummary a global variable, try this:
1) Make articleSummary local to your summarizeArticle() function.
2) In the class definition for your view controller with identifier "sbPopupVC", add an instance variable called something like articleSummaryText.
3) Get rid of the completion handler on summarizeArticle() and move all the code that was in there to the completion block of your URLSession API call.
4) In that completion block, right before self.addChildViewController(popupVC), add this line: popupVC.articleSummaryText = articleSummary
5) Finally, in viewDidLoad() of your popupVC, set summaryText.text = articleSummaryText.

issue passing data to segue.destination within function

I'm trying to make 2 API calls on Segue invoke and ultimately pass Array of Data from Second Call to CollectionView. With first call I'm getting one value catID, which I need in order to make the other call:
let searchEndpoint: String = MY_ENDPOINT
// Add auth key
let serviceCallWithParams = searchEndpoint + "?PARAMETER"
guard let url = URL(string: serviceCallWithParams) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)
// setting up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// making the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// error check
guard error == nil else {
print("error")
print(error)
return
}
// make sure we got data
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse JSON
do {
guard let catData = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject] else {
print("error converting data to JSON")
return
}
if let data = catData["data"] as? [String: Any] {
if let array = data["categories"] as? [Any] {
if let firstObject = array.first as? [String: Any] {
if let catId = firstObject["catId"] as? Int {
getTitles(catId: catId)
}
}
}
}
} catch {
print("error converting data to JSON")
return
}
}
task.resume()
And then getTitles function looks like this:
func getTitles(catId: Int) {
let catIdString = String(catId)
let titlesEndPoint: String = MY_ENDPOINT + catIdString
// Add auth key
let titlesEndPointWithParams = titlesEndPoint + "?PARAMETER"
guard let titlesUrl = URL(string: titlesEndPointWithParams) else {
print("Error: cannot create URL")
return
}
let titlesUrlRequest = URLRequest(url: titlesUrl)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: titlesUrlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET on listCategoryTitles")
print(error)
return
}
// make sure we got data
guard let titlesData = data else {
print("Error: did not receive data")
return
}
// parse the JSON
do {
guard let allTitles = try JSONSerialization.jsonObject(with: titlesData, options: []) as? [String: AnyObject] else {
print("error converting data to JSON")
return
}
if let titlesJson = allTitles["data"] as? [String: Any] {
if let titlesArray = titlesJson["titles"] as? Array<AnyObject> {
self.books = []
for (index, value) in titlesArray.enumerated() {
var book = Book()
book.bookTitle = value["title"] as? String
book.bookAuthor = value["author"] as? String
if let imageSource = value["_links"] as? Array<AnyObject> {
book.bookImageSource = imageSource[1]["href"] as? String
}
self.books?.append(book)
}
}
}
} catch {
print("error converting data to JSON")
return
}
}
task.resume()
}
Now when I put:
let resultsVC = segue.destination as? CollectionViewController
resultsVC?.books = self.books
outside function, in target controller I'm getting an empty array as output on first click, but on every next one I'm getting proper data.
When I try putting this inside function "getTitles" the output in CollectionViewController is "nil" every time.
Worth mentioning could be that I have "books" variable defined like so:
Main Controller:
var books: [Book]? = []
Collection Controller:
var books: [Book]?
and I have created type [Book] which is basically object with 3 string variables in separate struct.
All of the code above is encapsulated in
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowResults" {
Any help/guideline would be much appreciated!
When you make api call it will execute in background means asynchronously where as prepare(for:sender:) will call synchronously.
Now from your question it is looks like that you have create segue in storyboard from Button to ViewController, so before you get response from your api you are moved to your destination controller, to solved your issue you need to create segue from your Source ViewController to Destination ViewController and set its identifier. After that inside getTitles(catId: Int) method after your for loop perform segue on the main thread.
for (index, value) in titlesArray.enumerated() {
var book = Book()
book.bookTitle = value["title"] as? String
book.bookAuthor = value["author"] as? String
if let imageSource = value["_links"] as? Array<AnyObject> {
book.bookImageSource = imageSource[1]["href"] as? String
}
self.books?.append(book)
}
DispatchQueue.main.async {
self.performSegue(withIdentifier: "ShowResults", sender: nil)
}
After that inside your prepare(for:sender:) make changes like below.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowResults" {
let resultsVC = segue.destination as? CollectionViewController
resultsVC?.books = self.books
}
}

data with request completionhandler not always called

I am making an app where you can search for movies with the API of http://www.omdbapi.com/.
The problem I am having is with the completion handler of dataTaskWithRequest. If you click on one of the collectionView cell, you will go to the detailView of that selected movie. However it doesn't work all the time. I get an error saying: unexpectedly found nil while unwrapping. And that's because it doesn't go in the completion handler of dataTaskWithRequest but goes straight to the detailVC and try passing data in the title label, genre label, etc but there is no data.
I hope you guys know what the problem is, because I have tried and I don't see what the problem is.
Or, does this problem occurs because of something before? Because first I retrieve data from http://www.omdbapi.com/ using "by search" instead of "by ID". And from there I retrieve the ID and from that ID I retrieve data for my detailVC.
Here is my code:
// Go to detail view of selected movie
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let selectedMovieId = self.IDs[indexPath.row]
chosenMovieId = selectedMovieId
self.performSegueWithIdentifier("showDetail", sender: self)
}
// Preparations before going to the detail view of selected movie
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
_ = self.movieInfoFrom(searchMovie: chosenMovieId, segue: segue)
}
}
func movieInfoFrom(searchMovie movieId: String, segue: UIStoryboardSegue) {
let movieUrlString = "http://www.omdbapi.com/?i=\(movieId)&y=&plot=full&r=json"
let url = NSURL(string: movieUrlString)
print(movieUrlString)
let urlRequest = NSURLRequest(URL: url!)
let urlSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let urlTask = urlSession.dataTaskWithRequest(urlRequest) { (data, response, error) in
if error == nil {
// Convert data to JSON
let swiftyJSON = JSON(data: data!)
let title = swiftyJSON["Title"].string!
let runTime = swiftyJSON["Runtime"].string!
let genre = swiftyJSON["Genre"].string!
let plot = swiftyJSON["Plot"].string!
let rating = swiftyJSON["imdbRating"].string!
let year = swiftyJSON["Year"].string!
let poster = swiftyJSON["Poster"].string
self.infoResult = ["\(title)", "\(runTime)", "\(genre)", "\(plot)", "\(rating)", "\(year)"]
print("\(self.infoResult)")
let destinationVC = segue.destinationViewController as! MovieDetailController
destinationVC.movieDetails = self.infoResult
destinationVC.moviePoster = poster
}
}
urlTask.resume()
}
I tried to fix your code and explain with some comments:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let selectedMovieId = self.IDs[indexPath.row]
chosenMovieId = selectedMovieId
self.movieInfoFrom(searchMovie: chosenMovieId)
}
// Preparations before going to the detail view of selected movie
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
let destinationVC = segue.destinationViewController as! MovieDetailController
destinationVC.movieDetails = self.infoResult
destinationVC.moviePoster = poster
}
}
func movieInfoFrom(searchMovie movieId: String) {
let movieUrlString = "http://www.omdbapi.com/?i=\(movieId)&y=&plot=full&r=json"
let url = NSURL(string: movieUrlString)
print(movieUrlString)
let urlRequest = NSURLRequest(URL: url!)
let urlSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
// This is asynchronously, you can put a loading here
let urlTask = urlSession.dataTaskWithRequest(urlRequest) { (data, response, error) in
// Got response, stop loading here
if error == nil {
// Convert data to JSON
let swiftyJSON = JSON(data: data!)
let title = swiftyJSON["Title"].string!
let runTime = swiftyJSON["Runtime"].string!
let genre = swiftyJSON["Genre"].string!
let plot = swiftyJSON["Plot"].string!
let rating = swiftyJSON["imdbRating"].string!
let year = swiftyJSON["Year"].string!
// You can save the poster as local variable
let poster = swiftyJSON["Poster"].string
self.infoResult = ["\(title)", "\(runTime)", "\(genre)", "\(plot)", "\(rating)", "\(year)"]
print("\(self.infoResult)")
// This should be call on main thread
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("showDetail", sender: self)
}
}
}
urlTask.resume()
}
Try this code, with safe optionals
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
chosenMovieId = self.IDs[indexPath.row]
movieInfoFrom(searchMovie: chosenMovieId)
}
func movieInfoFrom(searchMovie movieId: String) {
let movieUrlString = "http://www.omdbapi.com/?i=\(movieId)&y=&plot=full&r=json"
let url = NSURL(string: movieUrlString)
print(movieUrlString)
let urlRequest = NSURLRequest(URL: url!)
let urlSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let urlTask = urlSession.dataTaskWithRequest(urlRequest) { (data, response, error) in
if error == nil && data != nil {
// Convert data to JSON
let swiftyJSON = JSON(data: data!)
let title = swiftyJSON["Title"].string ?? ""
let runTime = swiftyJSON["Runtime"].string ?? ""
let genre = swiftyJSON["Genre"].string ?? ""
let plot = swiftyJSON["Plot"].string ?? ""
let rating = swiftyJSON["imdbRating"].string ?? ""
let year = swiftyJSON["Year"].string ?? ""
let poster = swiftyJSON["Poster"].string
self.infoResult = ["\(title)", "\(runTime)", "\(genre)", "\(plot)", "\(rating)", "\(year)"]
print("\(self.infoResult)")
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("showDetail", sender: poster)
}
}
}
urlTask.resume()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail", let destinationVC = segue.destinationViewController as? MovieDetailController {
destinationVC.movieDetails = self.infoResult
destinationVC.moviePoster = sender as? String
}
}

Resources