About UICollectionView in IOS

UICollectionView, Manages an ordered collection of data item and present them using customizable layouts.

UICollectionView is same as the UITableView. UITableView manages a collection of data or information and display then on the screen in a single column layout whereas UICollectionView offers developers flexibility to present item using customize layout.

UICollectionView has three components:-

  1. Cell:

It is an instance of UICollectionViewCell . It represent a single item in the data collection.

  1. Supplementary views:

It is optional and usually used to implement the header or footer view of the sections.

  1. Decoration views:

It is another type of supplementary view but for decoration purpose only. It is not related to data collection. We create decoration view to enhance the visual appearance of the CollectionView.

Step 1:

Open the Excode and select the Single View Application.

UI Collection View

Step 2:

Create project with “ExCollectionView” name.

ExCollectionView

Step 3:

Open the StoryBoard and there is a ViewController and drag the CollectionVIew inside the ViewController .

And set the Add New Constraints.

UIViewController1

Step 4:

Select now the cell inside the UIViewController and add the UIImage in the UICollectionView cell and also set the UIImage constraints.

ViewController.swift

UICollectionView2

And open the ViewController.swift and add the extension of  UICollectionViewDataSource,UICollectionViewDelegatein the ViewCollection.swift.

And these three method in the ViewController.swift:

func numberOfSections(in collectionView: UICollectionView) -> Int {

        code

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        code

    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) ->      UICollectionViewCell {

        code

    }

UICollectionViewCel

After that select the UICollectionViewCell and set the name of the reuseIdentifier = “MyCollectionViewCell”

Using Assistant Editor, add an IBOutlet to CollectionView in ViewController.swift

@IBOutlet weak var collectionView: UICollectionView!

Create a new Cocoa Touch Class file (File > New > File… > iOS > Cocoa Touch Class). Name it MyCollectionViewCell. This class will hold the outlets for the views that you add to your cell in the storyboard.

ViewController

And open the ViewController.swift and add this code in the numberOfItemInSection in collectionview:

return

And go to the main story board and select the UIImage and set the image in the UIImage.

viewcontroller1

And also add one method in the viewcontroller.swift:

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:    UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return (indexPath.section == 0) ? CGSize(width: collectionView.bounds.size.width, height: 200) : CGSize(width: collectionView.bounds.size.width/2 – 2, height: 170)

    }

And after the execude your code

UIImageView

It should be look like this. If you want to add multi image in the UIImageView then you use the array and pass the image in the array and cell in the cellForRowAtIndexPath method.

Also Read- About Intents in Android

Play Audio Video With AVFoundation in iOS Swift 3.0

AVFoundation is a framework in iOS that lets you performs a video play, create, edit, or reencode media files.  AVFoundation framework that you can create play Audio and Video visual media play in swift iOS.

AVFoundatiin allow you to work on detail level with time based audiovisual data with this framework in iOS swift , you can create, edit ,analyze and re-encoded data media files in swift application , it llok like pretty basic feature set. However, with this AVFoundation framework you can do some usual things, like capture a stream   and   in real time, manipulate and play back the same capture media.

Getting Start:-

Let’s now start an your Application design;

  1. Open your xcode
  2. Create a new xcode project
  3. Chose a single View Application then
  4. Click on next button then,
  5. Give the product name as you like then
  6. Click again next button then,
  7. Save in your directory and click on the create button
  8. Now ready your empty project then,
  9. Select you device that you want run your project

AVFoundation

Now click on the this you seen iphone 7 plus then select your simulator device you want run your project application seen like this

AVFoundation1

Now goto the project navigator and select the main.Storyboard from the project navigator

  • Now select your View Controller and goto the editor menu select the navigation controller you will see that add a navigation controller in your main.stroyboard
  • Then now select the navigation controller you will seen that your navigation controller automatically make a initial view controller
  • Let’s come on the design your view controller select the object library and search a UIButton then drag  a four uibutton  like this

AVFoundation2

Now drag four UIButon in the view controller you can seen

AVFoundation3

Now come on the change the text name of our button in the view controller we have two option change the name of the view the button

  1. Select the button and double your button text will come on edit mode.
  2. If you have second one option select the button and goto the attribute inspector change the text name of your button

AVFoundation5

You see on the scren shot text name button change with AudioPlayer

  • Now ready your design for the click button paly the audio video and repeat the song and stop the song

AVFoundation6

  • Now goto the project navigator select the view controller

 

import AVFoundation

//MARK:- add this line below the import uikit

//Mark:- now make function to call audioplayer

func playAudio()

    {

// get random number for sound from the array

let intRandomNum = Int(arc4random_uniform(UInt32(arrAudio.count)))

// set URL of the sound

let soundURL = URL(fileURLWithPath: Bundle.main.path(forResource: arrAudio[intRandomNum], ofType: “wav”)!)

do

  {

   audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)

   audioPlayer.delegate = self

// check if audioPlayer is prepared to play audio

if (audioPlayer.prepareToPlay()){

      audioPlayer.play()

            }

        }

        catch(let error)

        {

            debugPrint(error.localizedDescription)

        }

    }

 

  • Now make object for audioPlayer with AVAudioPlayer() like this:

 

var audioPlayer = AVAudioPlayer()

// Mark:- now add delegate method

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AVAudioPlayerDelegate

{

// Mark now make to function for stop Audio

 

func stopAudio()

    {

        audioPlayer.stop()

        btnPlayAudioRepeatedly.isEnabled = true

        btnStopAudio.isEnabled = false

        playAudioRepeatedly = false

    }

 // mark function for get video from the iphone and directory

func getVideos()

    {

    let imagePickerController = UIImagePickerController()

imagePickerController.sourceType = .savedPhotosAlbum

imagePickerController.mediaTypes = [kUTTypeMovie as String]

imagePickerController.delegate = self

self.present(imagePickerController, animated: true, completion: nil)

    }

}

 

// Now created an object for Boolean value

 

var playAudioRepeatedly = true

 

// mark:- create array for playAudio data from your mobile and simulator

let arrAudio: [String] = [“chime_bell_ding”, “music_marimba_chord”, “pop_drip”]

//now make two @iboutlet weak var those create a memory for outlet:-

@IBOutlet weak var btnPlayAudioRepeatedly: UIButton!

@IBOutlet weak var btnStopAudio: UIButton!

//MARK: – AVAudioPlayerDelegate Methods

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool)

    {

        if (playAudioRepeatedly)

        {

            audioPlayer.play()

        }

    }

  • Now goto the object library and drag an AVKItPlayer View Controller

AVFoundation0

Now goto the project navigator and select the main project directory click on right open a list select the new file like this

Now create a new swift class that class will be cocoa touch class like this and click on the next button and give the class name VideoPlayerViewController and subclass should be AVPlayerViewController like this

AVFoundation02

After click next button open new window like seen this

AVFoundation03

Now create a new swift class with name will be VideoPlayerViewController import with these two libraries

import AVKit

import AVFoundation

//Mark: – now add a notification function for reachEndnotificationHandler

func playerDidReachEndNotificationHandler(notification: Notification)

    {

        print(“playerDidReachEndNotification”)

    }

//Mark: – this function use for load video

    func loadVideo(){

        videoPlayer = AVPlayer(url: videoURL)

        let playerVc = AVPlayerViewController()

        playerVc.player = videoPlayer

        NotificationCenter.default.addObserver(self, selector: #selector(playerDidReachEndNotificationHandler(notification:)), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: videoPlayer.currentItem)

        self.present(playerVc, animated: true)

        {

            playerVc.player?.play()

        }

    }

now do a thing that goto the click on main.storyboard select the AVKit player view controller and select the identity inspector give the class name VideoPlayerViewController and copy this class name paste the storyboard id box and Check the use storyboarb id This will work for the identifier

Now once again goto the view controller and create a uiimageaPickerControllerDelegate method

// MARK: – UIImagePickerControllerDelegate Methods

 func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){

self.dismiss(animated: true, completion: nil)

let videoPlayerViewController = self.storyboard!.instantiateViewController(withIdentifier: “VideoPlayerViewController”) as! VideoPlayerViewController videoPlayerViewController.videoURL = info[UIImagePickerControllerMediaURL] as? URL as URL!

self.navigationController!.pushViewController(videoPlayerViewController, animated: true)

    }

now last one thing add @ibaction for all button in the view controller

make an action for every button  and add functionality

//MARK: – Action Methods

 @IBAction func btnPlayAudioTapped(sender: AnyObject)

    {

        playAudio()

    }

@IBAction func btnPlayVideoTapped(sender: AnyObject)

    {

        getVideos()

    }

@IBAction func btnPlayAudioRepeatedlyTapped(sender: AnyObject)

    {

        btnPlayAudioRepeatedly.isEnabled = false

        btnStopAudio.isEnabled = true

        playAudioRepeatedly = false

        playAudio()

    }

@IBAction func btnStopAudioTapped(sender: AnyObject)

    {

        stopAudio()

}

Now one important thing add a string library into a plist  because if not add this stirng  library application give the run time error

Select the info plist in the project navigator click on the add button  like this

and tap on the pulse button select the srting library this

And now last and final step connect all @iboutlet, @ibAction with view controller

  • Now run your project it will run successfully

AVFoundation08

Now click on the ok button your simulator video will be show in the list and select those you chose and play the video like this after click on the ok button

AVFoundation09

Select video click that your video play successfully

AVFoundation00

Also Read- About UICollectionView in IOS

If you are, looking to Develop and design for your project then feel free to contact us at any time

Call Us- +91 9910781148, +1 8033353593
Email: company@tecorb.com
Skype- tecorb
“We maintain transparency with our customers. Our values and business ethics has given us repeated customers. We tend are proud to be a reliable outsourcing partner for many clients across the World.”