I am trying to implement the unsplash-photopicker-ios component in SwiftUI through the UIViewControllerRepresentable. The view starts successfully, but the unsplashPhotoPicker function does not work, it always returns nil, can someone tell me what the problem is.
import SwiftUI
import UnsplashPhotoPicker
struct UnsplashImagePicker: UIViewControllerRepresentable {
var urlUnsplashImage = [UnsplashPhoto]()
let configuration = UnsplashPhotoPickerConfiguration(
accessKey: "f99d21d6eb682196455dd29b621688aff2d525c7c3a7f95bfcb05d497f38f5dc",
secretKey: "ccff858162e795c062ce13e9d16a2cf607076d0eb185141e35b14f589b1cd713",
allowsMultipleSelection: false)
func makeUIViewController(context: UIViewControllerRepresentableContext<UnsplashImagePicker>) -> UnsplashPhotoPicker {
let unsplashImagePicker = UnsplashPhotoPicker(configuration: configuration)
unsplashImagePicker.delegate = context.coordinator
return unsplashImagePicker
}
func makeCoordinator() -> UnsplashImagePicker.Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UnsplashPhotoPickerDelegate, UINavigationControllerDelegate {
var parent: UnsplashImagePicker
init(_ parent: UnsplashImagePicker) {
self.parent = parent
}
func unsplashPhotoPicker(_ photoPicker: UnsplashPhotoPicker, didSelectPhotos photos: [UnsplashPhoto]) {
print(photos)
}
func unsplashPhotoPickerDidCancel(_ photoPicker: UnsplashPhotoPicker) {
print("Unsplash photo picker did cancel")
}
}
func updateUIViewController(_ uiViewController: UnsplashPhotoPicker, context: UIViewControllerRepresentableContext<UnsplashImagePicker>) {
}
}
You need to present the Unsplashpicker from a different UIViewcontroller.The Unsplashpicker could not be directly used as UIViewControllerRepresentable.
import SwiftUI
import UIKit
import UnsplashPhotoPicker
struct UnsplashPresenter: UIViewControllerRepresentable {
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
//
}
func makeUIViewController(context: Context) -> UIViewController {
return UnsplashPickerVC()
}
typealias UIViewControllerType = UIViewController
}
class UnsplashPickerVC: UIViewController, UnsplashPhotoPickerDelegate {
func unsplashPhotoPicker(_ photoPicker: UnsplashPhotoPicker, didSelectPhotos photos: [UnsplashPhoto]) {
print("=============== New Photo Selected =============== \n")
print(photos)
}
func unsplashPhotoPickerDidCancel(_ photoPicker: UnsplashPhotoPicker) {
print("did cancel")
}
var outputImage = UIImage(named: "Instructions.png")
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton()
button.frame = CGRect(x: (self.view.frame.size.width / 2) - 25, y: (self.view.frame.size.height / 2) - 50, width: 100, height: 50)
button.backgroundColor = UIColor.blue
button.setTitle("Pick Images", for: .normal)
button.addTarget(self, action: #selector(pickImages), for: .touchUpInside)
self.view.addSubview(button)
}
#objc func pickImages(sender: UIBarButtonItem) {
let configuration = UnsplashPhotoPickerConfiguration(
accessKey: "<Your Access Key >",
secretKey: "<Your Secret Key >"
)
let photoPicker = UnsplashPhotoPicker(configuration: configuration)
photoPicker.photoPickerDelegate = self
present(photoPicker, animated: true, completion: nil)
}
}
Related
I'm new in Swift and ARKit. For some reason the SCNNode node I'm trying to display is not showing up. I'm working with SwiftUI. I defined in the next code block the function addNode that should render the node.
import Foundation
import ARKit
import SwiftUI
// MARK: - ARViewIndicator
struct ARViewIndicator: UIViewControllerRepresentable {
typealias UIViewControllerType = ARView
func makeUIViewController(context: Context) -> ARView {
return ARView()
}
func updateUIViewController(_ uiViewController:
ARViewIndicator.UIViewControllerType, context:
UIViewControllerRepresentableContext<ARViewIndicator>) { }
}
class ARView: UIViewController, ARSCNViewDelegate {
var arView: ARSCNView {
return self.view as! ARSCNView
}
override func loadView() {
self.view = ARSCNView(frame: .zero)
}
override func viewDidLoad() {
super.viewDidLoad()
arView.delegate = self
arView.scene = SCNScene()
}
// MARK: - Functions for standard AR view handling
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let configuration = ARWorldTrackingConfiguration()
arView.debugOptions = [.showFeaturePoints,
.showWorldOrigin]
arView.session.run(configuration)
arView.delegate = self
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
arView.session.pause()
}
func addNode(){
let node = SCNNode()
node.geometry = SCNBox(width: 0.1,
height: 0.1,
length: 0.1,
chamferRadius: 0)
node.geometry?.firstMaterial?.diffuse.contents = UIColor.blue
node.position = SCNVector3(0,0,0.3)
arView.scene.rootNode.addChildNode(node)
arView.delegate = self
print(123)
}
// MARK: - ARSCNViewDelegate
func sessionWasInterrupted(_ session: ARSession) {}
func sessionInterruptionEnded(_ session: ARSession) {}
func session(_ session: ARSession, didFailWithError error: Error)
{}
func session(_ session: ARSession, cameraDidChangeTrackingState
camera: ARCamera) {}
}
... and that function is invoked when clicking the button "HOME"
import SwiftUI
import ARKit
// MARK: - NavigationIndicator
struct NavigationIndicator: UIViewControllerRepresentable {
typealias UIViewControllerType = ARView
func makeUIViewController(context: Context) -> ARView {
return ARView()
}
func updateUIViewController(_ uiViewController:
NavigationIndicator.UIViewControllerType, context:
UIViewControllerRepresentableContext<NavigationIndicator>) { }
}
struct ContentView: View {
#State var page = "Home"
var body: some View {
VStack {
ZStack {
NavigationIndicator()
VStack {
Spacer()
HStack {
Button("Home") {
let ar = ARView();
ar.addNode()
}.padding()
.background(RoundedRectangle(cornerRadius: 10)
.foregroundColor(Color.white).opacity(0.7))
Spacer()
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Do you know why it's not showing up ?
Thanks in advance !
Use this approach for SceneKitView:
import SwiftUI
import ARKit
struct SceneKitView: UIViewRepresentable {
let arView = ARSCNView(frame: .zero)
#Binding var pressed: Bool
#Binding var node: SCNNode
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
final class Coordinator: NSObject, ARSCNViewDelegate {
var control: SceneKitView
init(_ control: SceneKitView) {
self.control = control
}
func renderer(_ renderer: SCNSceneRenderer,
updateAtTime time: TimeInterval) {
if control.pressed {
self.control.node = self.addCube()
self.control.arView.scene.rootNode.addChildNode(control.node)
}
}
fileprivate func addCube() -> SCNNode {
control.node.geometry = SCNBox(width: 0.25,
height: 0.25,
length: 0.25,
chamferRadius: 0.01)
control.node.geometry?.firstMaterial?.diffuse.contents = UIColor.blue
control.node.geometry?.firstMaterial?.lightingModel = .phong
control.node.position = SCNVector3(0, 0,-2)
return control.node
}
}
func makeUIView(context: Context) -> ARSCNView {
arView.scene = SCNScene()
arView.delegate = context.coordinator
arView.autoenablesDefaultLighting = true
arView.debugOptions = .showFeaturePoints
// arView.allowsCameraControl = true
let config = ARWorldTrackingConfiguration()
arView.session.run(config)
return arView
}
func updateUIView(_ uiView: ARSCNView,
context: Context) { }
}
Then use this code for ContentView.
struct ContentView: View {
#State var pressed: Bool = false
#State var node = SCNNode()
var body: some View {
ZStack {
SceneKitView(pressed: $pressed, node: $node)
VStack {
Spacer()
HStack {
Button("Blue Cube") {
pressed.toggle()
}.padding()
.foregroundColor(.red)
Spacer()
}
}
}
}
}
P.S.
However, a strange issue occurs with ARSCNView in Simulator – after pressing a button a SCNBox appears only after tapping a screen with .allowsCameraControl = true.
I have ViewController1 that goes to ViewModel and then to Coordinator to present ViewController2.
The problem is: I need to know when VC2 was dismissed on VC1.
What I need to do: When VC2 is dismissed, I need to reload my table from VC1.
I can not use Delegate since I cant communicate between then (because of Coordinator).
Any help please?
Adding some code: My Coordinator:
public class Coordinator: CoordinatorProtocol {
public func openVC1() {
let viewModel = ViewModel1(coordinator: self)
guard let VC1 = ViewControllerOne.instantiate(storyboard: storyboard, viewModel: viewModel) else {
return
}
navigationController?.pushViewController(VC1, animated: true)
}
public func openVC2() {
let viewModel = ViewModel2()
guard let alertPriceDeleteVC = ViewControllerTwo.instantiate(storyboard: storyboard, viewModel: viewModel) else {
return
}
let nav = UINavigationController(rootViewController: VC2)
navigationController?.present(nav, animated: true, completion: nil)
}
CoordinatorProtocol:
public protocol CoordinatorProtocol {
func openVC1()
func openVC2()
}
My ViewModel1 calling VC2 through coordinatorDelegate:
func openVC2() {
coordinator.openVC2()
}
What I do when I finish ViewController2 and send user back do VC1:
navigationController?.dismiss(animated: true, completion: nil)
You need to to assign delegate value from prepare. Or you can assign delegate with initialize RedScreenVC(self) from your ViewController if u don't want to use storyboard/xib.
import UIKit
class ViewController: UIViewController, NavDelegate {
func navigate(text: String, isShown: Bool) {
print("text: \(text) isShown: \(isShown)")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "RedScreenVC") {
let redScreenVC = segue.destination as? RedScreenVC
redScreenVC?.delegate = self
}
}
#IBAction func nextPageButtonEventLustener(_ sender: Any) {
performSegue(withIdentifier: "RedScreenVC", sender: sender)
}
}
import UIKit
protocol NavDelegate {
func navigate(text: String, isShown: Bool)
}
class RedScreenVC: UIViewController {
weak var delegate: NavDelegate?
var redView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
var navigateButton: UIButton = {
let button = UIButton(frame: CGRect(x: 200, y: 350, width: 150, height: 50))
button.setTitle("Navigate", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
button.backgroundColor = .blue
return button
}()
#objc func buttonAction(){
if self.redView.backgroundColor == .gray {
self.redView.backgroundColor = .systemPink
}
self.delegate.navigate(text:"", isShown: true)
}
override func viewDidLoad() {
navigateButton.layer.cornerRadius = 25
redView.backgroundColor = UIColor.gray
delegate.navigate(text: "Navigation Success", isShown: true)
view.addSubview(redView)
view.addSubview(navigateButton)
}
}
If you do not want to use storyboard.
let redScreenVC = RedScreenVC()
redScreenVC.delegate = self
class RedScreenVC: UIViewController {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init() {
super.init(nibName: nil, bundle: nil)
self.initialize()
}
func initialize() {
self.view.backgroundColor=CustomColor.PAGE_BACKGROUND_COLOR_1
//From here you need to create your email and password textfield
}
}
I'm trying to create a photo album via UIImagePicker into a CollectionView and cannot get it to segue to that same photo again in a detailed UIViewController. Pulling my hair out and this is just a tutorial as I have just started coding!
Can anyone tell me what I'm doing wrong?
Here is my ViewController:
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate {
#IBOutlet private weak var addButton: UIBarButtonItem!
#IBOutlet private weak var collectionView:UICollectionView!
#IBOutlet private weak var trashButton:UIBarButtonItem!
var testItems = [Person]()
var stormTrooperCollectionArray: [UIImage] = [#imageLiteral(resourceName: "StormTrooper-3052-423a-8c57-7220081e1585_800x"), #imageLiteral(resourceName: "ST3"), #imageLiteral(resourceName: "ST2"), #imageLiteral(resourceName: "ST4")]
#IBAction func addItem() {
addNewPerson()
}
#IBAction func trashItem(_ sender: Any) {
if let selectedItems = collectionView.indexPathsForSelectedItems {
let itemsForDeletion = selectedItems.map{$0.item}.sorted().reversed()
for item in itemsForDeletion {
testItems.remove(at: item)
}
collectionView.deleteItems(at: selectedItems)
}
}
#objc func refresh() {
addItem()
collectionView.refreshControl?.endRefreshing()
}
override func viewDidLoad() {
super.viewDidLoad()
// Set up a 3-column Collection View
let width = (view.frame.size.width - 20) / 3
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width:width, height:width)
// Refresh Control
let refresh = UIRefreshControl()
refresh.addTarget(self, action: #selector(self.refresh), for: UIControlEvents.valueChanged)
collectionView.refreshControl = refresh
// Edit
navigationItem.leftBarButtonItem = editButtonItem
navigationController?.isToolbarHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DetailSegue" {
if let dest = segue.destination as? DetailsViewController,
let index = sender as? IndexPath {
dest.detailedImageHi = stormTrooperCollectionArray [index.row]
}
}
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
navigationController?.isToolbarHidden = !editing
addButton.isEnabled = !editing
trashButton.isEnabled = editing
collectionView.allowsMultipleSelection = editing
let indexes = collectionView.indexPathsForVisibleItems
for index in indexes {
let cell = collectionView.cellForItem(at: index) as! CollectionViewCell
cell.isEditing = editing
}
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UIImagePickerControllerDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return stormTrooperCollectionArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
//cell.titleLabel.text = stormTrooperCollectionArray[indexPath.row]
cell.selectionImage.image = stormTrooperCollectionArray[indexPath.row]
cell.isEditing = isEditing
return cell
}
#objc func addNewPerson() {
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.delegate = self
present(picker, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let image = info[UIImagePickerControllerEditedImage] as? UIImage else { return }
let imageName = UUID().uuidString
let imagePicture = getDocumentsDirectory()
if let jpegData = UIImageJPEGRepresentation(image, 80) {
try? jpegData.write(to: imagePicture)
}
//let detailedItem = Person(imageHi: imageName)
//testItems.append(detailedItem)
let detailedItem = Person(imageHi: imageName)
//KEEPS THROWING AN ERROR HERE WHICH SAYS: Cannot convert value of type 'String' to expected argument type 'UIImage'
stormTrooperCollectionArray.append(detailedItem)
collectionView?.reloadData()
dismiss(animated: true)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if !isEditing {
performSegue(withIdentifier: "DetailSegue", sender: indexPath)
}
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
}
Here is my VC for the Cell in the CollectionView:
import UIKit
class CollectionViewCell: UICollectionViewCell {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var selectionImage: UIImageView!
}
Here is my VC for the Detailed View Controller:
import UIKit
class DetailsViewController: UIViewController {
var selection: String!
var detailedImageHi: UIImage!
#IBOutlet private weak var detailsLabel: UILabel!
#IBOutlet private weak var detailedImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
detailsLabel.text = selection
detailedImage.image = detailedImageHi
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Here is my VC for the NSObject Swift File:
import UIKit
class Person: NSObject {
var imageHi: UIImage
init(imageHi: UIImage){
self.imageHi = imageHi
}
}
In your code the UIImage is image and not imageName:
guard let image = info[UIImagePickerControllerEditedImage] as? UIImage else { return }
So all you have to do is pass the right argument to the constructor of Person:
let detailedItem = Person(imageHi: image)
imageName is a random string generated via UUID().uuidString, and used in this code to save the image to the documents directory with a random and unique name.
In my project has 2 ViewControllers (ViewController and DetailViewController). On the first there are table view in UIScrollview. On the second - buttons in UICollectionView with images and links. When i popup in DetailViewController many times, the app starts slow down, and i see the leak memory on graph. Also in Debug memory i see 18 object of CollectionViewCell and 3 DetailViewController, First leak of CellProps i solve by:
override func viewDidDisappear(_ animated: Bool) {
btnArray.removeAll()
How to solve this memory leak?
ViewController.swift
import UIKit
import BetterSegmentedControl
import Firebase
class ViewController: UIViewController, UIScrollViewDelegate, UITableViewDelegate {
var ICOListGoingOn = [ICOs] ()
var ICOListEnded = [ICOs] ()
var ICOListnotstarted = [ICOs] ()
#objc func reload(n: NSNotification) {
SaveLikedArray()
self.icoArraySort()
let slide = SlideView(frame: CGRect(x: view.frame.width * CGFloat(0), y: 0, width: view.frame.width, height: slideScrollView.frame.height))
slide.ICO = ICOListLiked
slide.delegate = self
slideScrollView.addSubview(slide)
}
extension ViewController: SlideViewDelegate{
func tableCellSelected(tableView: UITableView, indexPath: IndexPath, ico: ICOs) {
// print("Table tag : \(tableView.tag) Selcted Row : \(indexPath.row) Selected Value : \(ico)")
if let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController{
controller.ICO = ico
ICOId = ico.ICOId
self.navigationController?.pushViewController(controller, animated: true)
}
}
}
CollectionViewCell.swift
import UIKit
class CellProps {
var image: UIImage!
var url: String!
init (image: UIImage, url: String) {
self.image = image
self.url = url
}
deinit {
print("CellProps")
}
}
protocol CollectionViewCellDelegate {
func didButtonClick(url: String)
}
class CollectionViewCell: UICollectionViewCell {
var delegate: CollectionViewCellDelegate!
weak var CellItem: CellProps!
#IBOutlet weak var btnICONOutlet: UIButton!
#IBAction func btnICONAction(_ sender: Any) {
delegate?.didButtonClick(url: CellItem.url)
}
func setCell(cell: CellProps) {
CellItem = cell
CellItem.url = cell.url
btnICONOutlet.setImage(cell.image, for: .normal)
}
deinit {
print("CollectionViewCell")
}
}
DetailViewController.swift
import UIKit
class DetailViewController: UIViewController {
var ICO: ICOs!
var btnArray: [CellProps] = []
var timer: Timer?
#IBOutlet weak var outCollectioView: UICollectionView!
#IBOutlet weak var btnLike: LikeButton!
#IBAction func btnLikeAction(_ sender: Any) {
if !btnLike.isOn {
let ind = CountLikedArray(id: ICO.ICOId)
if ind != -1 {
ICOListLiked.remove(at: ind)
lblLike.text = "Вы еще не лайкнули проект"
}
}
if btnLike.isOn {
let ind = CountLikedArray(id: ICO.ICOId)
if ind == -1{
ICOListLiked.append(self.ICO)
lblLike.text = "Вам нравится проект"
}
}
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "del"), object: nil)
}
func FillButtonArray () {
for value in ICO.news.values {
var btn : CellProps!
if value.lowercased().range(of:"t.me") != nil {
btn = CellProps(image: #imageLiteral(resourceName: "telegram"), url: value)
}
else if value.lowercased().range(of:"bitcointalk.org") != nil {
btn = CellProps(image: #imageLiteral(resourceName: "bitcoin"), url: value)
} else {
btn = CellProps(image: #imageLiteral(resourceName: "link"), url: value)
}
btnArray.append(btn)
}
}
deinit {
print("deinit detail")
}
override func viewDidDisappear(_ animated: Bool) {
btnArray.removeAll()
timer = nil
outCollectioView = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension DetailViewController: UICollectionViewDelegate, UICollectionViewDataSource, CollectionViewCellDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return btnArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let ICONs = btnArray[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.setCell(cell: ICONs)
cell.delegate = self
return cell
}
func didButtonClick(url: String) {
let ICONURL = URL (string: url)!
UIApplication.shared.open(ICONURL as URL)
}
}
if i debug memory graph there are 3 DatailViewController, and 18 CollectionViewCell
I found lazy way to solve self of my problem, it's
outCollectioView.removeFromSuperview()
btnLike.removeFromSuperview()
But DetailViewController still increasing (((
How to create array of multiple mp4 or mov files in swift. I was able to display the single video in uiwebview. I have pagecontrol to display some text but I need to display different videos same like texts. When the page control starts it should display next video. Here is the code for first view controller and page view controller.
import UIKit
class ViewController: UIViewController,UIPageViewControllerDataSource {
//var pageImages:NSArray!
var ouotes: NSArray!
var video: NSArray!
var pageViewController:UIPageViewController!
#IBOutlet weak var GenerateNumbers: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
video = ["2.mov", "1.mov", "4.mov"]
ouotes = ["sometext" ]
// NSArray(objects:"ap", "bg", "gfb")
/* UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "money")?.draw(in: self.view.bounds)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)*/
self.pageViewController = self.storyboard?.instantiateViewController(withIdentifier: "MyPageViewController") as! UIPageViewController
self.pageViewController.dataSource = self
let initialContenViewController = self.pageTutorialAtIndex(0) as ContentHolder
self.pageViewController.setViewControllers([initialContenViewController], direction: UIPageViewControllerNavigationDirection.forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRect(x: 0, y: 100, width: self.view.frame.size.width, height: self.view.frame.size.height-100)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMove(toParentViewController: self)
// 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 pageTutorialAtIndex(_ index: Int) -> ContentHolder {
let pageContentViewController = self.storyboard?.instantiateViewController(withIdentifier: "ContentHolder") as! ContentHolder
pageContentViewController.imageFileName = ouotes[index] as! String
pageContentViewController.videoFileName = video [index] as! String
pageContentViewController.pageIndex = index
return pageContentViewController
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?
{
let viewController = viewController as! ContentHolder
var index = viewController.pageIndex as Int
if (index == 0 || index == NSNotFound) {
return nil
}
index -= 1
return self.pageTutorialAtIndex(index)
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?
{
let viewController = viewController as! ContentHolder
var index = viewController.pageIndex as Int
if ((index == NSNotFound)) {
return nil
}
index += 1
if (index == ouotes.count) {
return nil
}
if (index == video.count) {
return nil
}
return self.pageTutorialAtIndex(index)
}
public func presentationCount(for pageViewController: UIPageViewController) -> Int {
return ouotes.count
}
public func presentationIndex(for pageViewController: UIPageViewController) -> Int{
return 0
}
}
And for the pagecontrol view where texts and videos should be displayed
import Foundation
import UIKit
import AVKit
import AVFoundation
class ContentHolder: UIViewController {
var imageFileName: String!
var videoFileName: String!
var pageIndex:Int!
#IBOutlet weak var EuroScrollView: UIScrollView!
#IBOutlet weak var VideoView: UIWebView!
#IBOutlet weak var myLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// let fileURL = NSURL (fileURLWithPath: "/Users/nafu/Desktop/2.mov")
VideoView.loadHTMLString("<iframe width = \"\(self.VideoView.frame.width) \" height =\"\(self.VideoView.frame.height)\" src = \"\(videoFileName)\"> </iframe>", baseURL: nil)
myLabel.text = imageFileName
myLabel.numberOfLines = 0
myLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
myLabel.font = UIFont(name:"HelveticaNeue-Bold", size: 15.0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Thanks in advance.