Make class in swift3 with AVplayer - avplayer

this is the code :
import Foundation
import UIKit
import AVFoundation
class MP3PLAYER {
var player = AVPlayer()
func PLAY (){
player.play()
}
init ( url_ : String , autoplay_ : String , player_ : AVPlayer) {
player = player_
let url = url_
let playerItem = AVPlayerItem( url:URL( string:url )! )
player = AVPlayer(playerItem:playerItem)
player.rate = 1.0;
if autoplay_ == "YES" {
player.play()
print("autoplay is on")
}
}
}
In this code there is no error even warning.
Simply player wont play . If i put code direct in viewController than player working ...
I use class on this way in viewController:
<code>
import UIKit
import AVFoundation
class Mp3Stream_example: UIViewController {
var player = AVPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let STREAM1 = MP3PLAYER(url_: "http://listen.181fm.com:181-soul_128k.mp3" , autoplay_: "YES" , player_ : player )
STREAM1.player.play()
//player.play()
.....
</code>

Your player, STREAM1, is going out of scope and is being deallocated, hence no sound. Make it a class member variable instead of a local variable. e.g.
class Mp3Stream_example: UIViewController {
let STREAM1 = MP3PLAYER(url_: "http://listen.181fm.com:181-soul_128k.mp3" , autoplay_: "YES" , player_ : AVPlayer() )
....
P.S. you've got extra AVPlayers that you don't need.

Related

show image in imageview from string in swift 4 without url

I have a project in swift 4. I need to get an image from the api but I get error as "Cannot assign value of type 'String' to type 'UIImage?'".The codes of my project is:
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController {
#IBOutlet weak var coachProfile: UIImageView!
var responseArr = [JSON]()
override func viewDidLoad() {
super.viewDidLoad()
getCoachList()
}
func getCoachList() {
let url = "http://test.ilovecoach.com/api/student"
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let loader = appDelegate.showLoading()
WebServices.sharedInstance.get(toURL: url, successHandler: { (jsonData) in
print("messLists: \(jsonData)")
self.responseArr = jsonData.arrayValue
loader.removeFromSuperview()
let avatar = self.responseArr[0]["photo"].stringValue
print("CoachAvatar",avatar) // gives: 12.png
self.coachProfile.image = avatar //gives error as:Cannot assign value of type 'String' to type 'UIImage?'
}) { (error) in
}
}
}
I have an get method api which gives response as :
[
{
"name" : "Modi",
"title" : "d'Etat",
"id" : 12,
"photo" : "12.png"
}
]
Now, I need to get image named "photo" to coachprofile imageview. How can I solve this in swift 4?
Use this :
self.coachProfile.image = UIImage(named: avatar)

How do i add the Menu controller to any UiViewController , other than the rootview?

I am trying just to display the floating Menu on a separate view controller that is not the rootview ? Normally i just add it to the rootview controller.
let menuController = AppMenuController(rootViewController: toolbarController)
let navigationController = AppNavigationDrawerController(rootViewController: menuController, leftViewController: leftViewController,rightViewController: rightViewController)
let statusController = AppStatusBarController(rootViewController: navigationController)
window = UIWindow(frame: Screen.bounds)
window!.rootViewController = statusController
window!.makeKeyAndVisible()
let main: MainViewController = {
return UIStoryboard.viewController(identifier: "MainViewController") as! MainViewController}()
let newView = AppMenuController(rootViewController: main)
self.present(allergyView, animated: false, completion: nil)
Add the Menu as a property of the UIViewController. For example:
class ViewController: UIViewController {
fileprivate let menu = Menu()
fileprivate let baseSize = CGSize(width: 64, height: 64)
open override func viewDidLoad() {
super.viewDidLoad() {
prepareMenu()
}
}
extension MenuController {
fileprivate func prepareMenu() {
menu.zPosition = 1000
menu.baseSize = baseSize
view.layout(menu)
.size(baseSize)
.bottom(24)
.right(24)
}
}
In cases where you would not want to use the Material controllers with root view controllers, you should be able to look at the setup code in those controllers to see the code necessary to add the component they manage, for example MenuController.
All the best :)

Different info for different pin annotations

I have two different pins placed on my mapview. I have an info button on each. The info buttons will segue to the a UIViewController that has a Image view (to hold a picture of the place) and a Text label ( To hold info about the place).
My problem is how can I generate the Info and picture depending on which pin annotation button was selected. The last function is the one used in order to segue to the info view controller.
class GetToTheStart: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
//map view outlet
#IBOutlet weak var mapView: MKMapView!
//defining use of location manager
let myLocMgr = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
//setting up location request
myLocMgr.desiredAccuracy = kCLLocationAccuracyBest
myLocMgr.requestWhenInUseAuthorization()
myLocMgr.startUpdatingLocation()
myLocMgr.delegate = self
mapView.delegate = self
// coordinates of desired locations for pins
var zoo1 = CLLocationCoordinate2DMake(53.347439, -6.291820)
var town1 = CLLocationCoordinate2DMake(53.347247, -6.290865)
//setting up pin 1 annotation (the zoo)
var zoopin = MKPointAnnotation()
zoopin.coordinate = zoo1
zoopin.title = "Dublin Zoo"
zoopin.subtitle = "This this the zoo"
mapView.addAnnotation(zoopin)
//setting up pin 2 annotation (the town)
var townpin = MKPointAnnotation()
townpin.coordinate = zoo1
townpin.title = "Dublin town"
townpin.subtitle = "This this the town"
mapView.addAnnotation(townpin)
}
//setting up Pin callout button for segue
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
}
let reuseIdentifier = "pin"
var pin = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseIdentifier) as? MKPinAnnotationView
if pin == nil {
pin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
pin!.pinColor = .Red
pin!.canShowCallout = true
pin!.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure)
} else {
pin!.annotation = annotation
}
return pin
}
//performing segue from info button to infoViewController
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
performSegueWithIdentifier("info", sender: view)
}
For this you need to override below method. Here we will get the annotationView which will trigger the segue.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "info") {
if let annotation = sender as? MKAnnotationView {
let detailViewController = segue.destinationViewController as! DetailViewController
detailViewController.titleText = annotation.annotation?.title ?? ""
detailViewController.detaileText = annotation.annotation?.subtitle ?? ""
}
}
}
And in the detailViewController is same as your infoViewController and here I have two labels and for that I have two public variables. This is just to avoid error because at this point we don't have the label objects.
Here is the code for my DetailViewController.
import UIKit
class DetailViewController: UIViewController {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var detailLabel: UILabel!
var titleText: String? { didSet { updateUI() } }
var detaileText: String? { didSet { updateUI() } }
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}
private func updateUI() {
self.titleLabel?.text = self.titleText
self.detailLabel?.text = self.detaileText
}
}

How do you show a blue dot instead of a Pin when showing current location in mapview?

How do you show a blue dot instead of a Pin when showing current location in map view? at the moment the code illustrates a red pin that shows the users current location as the user moves around. How can i convert this to the blue dot that apple use?
import UIKit
import MapKit
class ViewController: UIViewController,CLLocationManagerDelegate {
#IBOutlet weak var myMapView: MKMapView!
let myLocMgr = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
myLocMgr.desiredAccuracy = kCLLocationAccuracyBest
myLocMgr.requestWhenInUseAuthorization()
myLocMgr.startUpdatingLocation()
myLocMgr.delegate = self
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// get most recient coordinate
let myCoor = locations[locations.count - 1]
//get lat & long
let myLat = myCoor.coordinate.latitude
let myLong = myCoor.coordinate.longitude
let myCoor2D = CLLocationCoordinate2D(latitude: myLat, longitude: myLong)
//set span
let myLatDelta = 0.05
let myLongDelta = 0.05
let mySpan = MKCoordinateSpan(latitudeDelta: myLatDelta, longitudeDelta: myLongDelta)
let myRegion = MKCoordinateRegion(center: myCoor2D, span: mySpan)
//center map at this region
myMapView.setRegion(myRegion, animated: true)
//add anotation
let myAnno = MKPointAnnotation()
myAnno.coordinate = myCoor2D
myMapView.addAnnotation(myAnno)
}
#IBAction func stop(sender: AnyObject) {
myLocMgr.stopUpdatingLocation()
}
#IBAction func resume(sender: AnyObject) {
myLocMgr.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
self.myMapView.showsUserLocation = true
showsUserLocation is what you need. It's MKMapView property set it in viewDidLoad or using IB (if possible). You don't need to do any extra stuff in LocationManager's delegate didUpdateLocations, just set it the MKMapView will do the rest of the stuff

How do I detect Tap and Hold on a pin in MKMapView?

The title says it all. I'm trying to detect a tap on a pin in a MKMapView and I don't even know where to begin. Its not an UIView, so I can't add a gesture recognizer and I can't find a UIView in MKPlaceMark to add it.
You're question is not very clear but you can do like this:
import UIKit
import MapKit
protocol HandleMapSearch: class {
func dropPinZoomIn(placemark:MKPlacemark)
}
class ViewController: UIViewController {
func getDirections(){
// Here you can put anythings like:
guard let selectedPin = selectedPin else { return }
let mapItem = MKMapItem(placemark: selectedPin)
let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
mapItem.openInMapsWithLaunchOptions(launchOptions)
}
}
extension ViewController : MKMapViewDelegate {
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?{
guard !(annotation is MKUserLocation) else { return nil }
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
}
pinView?.pinTintColor = UIColor.orangeColor() // The pin's color
pinView?.canShowCallout = true // To set dialogue bubbles of the pin.
let smallSquare = CGSize(width: 30, height: 30)
let button = UIButton(frame: CGRect(origin: CGPointZero, size: smallSquare)) // To initialize the button in the dialogue bubbles of the pin.
button.addTarget(self, action: #selector(ViewController.getDirections), forControlEvents: .TouchUpInside) // To set and initialize the button.
pinView?.leftCalloutAccessoryView = button
return pinView
}
}
You can have more details in Thorn web site

Resources