Created
September 29, 2018 05:03
-
-
Save Muneefm/db1e1eba25825f1fd8fe08a06b07b399 to your computer and use it in GitHub Desktop.
IOS swift network request
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
// | |
// ViewController.swift | |
// Intercept API demo | |
// | |
// Created by Muneef m on 29/9/18. | |
// Copyright © 2018 Muneef m. All rights reserved. | |
// | |
import UIKit | |
class ViewController: UIViewController { | |
let URL = "https://728b324c2a.to.intercept.rest/" | |
// Original Url = https://raw.githubusercontent.com/Muneefm/demo_data/master/movie.json | |
// Intercept Url = https://728b324c2a.to.intercept.rest/ | |
let imageBaseUrl = "https://image.tmdb.org/t/p/w500" | |
@IBAction func buttonAction(_ sender: Any) { | |
requestData() | |
} | |
@IBOutlet weak var movieTitle: UILabel! | |
@IBOutlet weak var moviePoster: UIImageView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
func requestData() { | |
let url = Foundation.URL(string: URL) | |
let session = URLSession.shared | |
let task = session.dataTask(with: url!) | |
{ | |
(data, response, error ) in | |
do { | |
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject> | |
let title = json["original_title"] as! String | |
let imagePath = json["poster_path"] as! String | |
// image | |
do { | |
let url = Foundation.URL(string: self.imageBaseUrl+imagePath) | |
let data = try Data(contentsOf: url!) | |
DispatchQueue.main.async { | |
self.movieTitle.text = title | |
self.moviePoster.image = UIImage(data: data) | |
} | |
} | |
catch { | |
print("error") | |
} | |
} | |
catch { | |
print("error") | |
} | |
} | |
task.resume() | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment