Hi im just wondering why isnt my MapView function is not being called. I am trying to draw a line between points but all is showing is just the center location.
Thanks in advance.
import UIKit
import CoreLocation
import MapKit
class ThirdViewController: UIViewController , CLLocationManagerDelegate {
#IBOutlet weak var theMap: MKMapView!
#IBOutlet weak var theLabel: UILabel!
var manager:CLLocationManager!
var myLocations: [CLLocation] = []
override func viewDidLoad() {
super.viewDidLoad()
//Setup our Location Manager
manager = CLLocationManager()
self.manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
//Setup our Map View
// theMap.delegate = self
theMap.mapType = MKMapType.Standard
theMap.showsUserLocation = true
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
theLabel.text = "\(locations[0])"
myLocations.append(locations[0] as CLLocation)
let spanX = 0.007
let spanY = 0.007
var newRegion = MKCoordinateRegion(center: theMap.userLocation.coordinate, span: MKCoordinateSpanMake(spanX, spanY))
theMap.setRegion(newRegion, animated: true)
println("not yet ")
if (myLocations.count > 1){
println("here ")
var sourceIndex = myLocations.count - 1
var destinationIndex = myLocations.count - 2
let c1 = myLocations[sourceIndex].coordinate
let c2 = myLocations[destinationIndex].coordinate
var a = [c1, c2]
var polyline = MKPolyline(coordinates: &a, count: a.count)
theMap.addOverlay(polyline)
}
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
println("sad")
if overlay is MKPolyline {
println("aadsfsad")
var polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 4
return polylineRenderer
}
return nil
}
}
in ios8+ MapView didn`t load LocationCoordinate automatically. If we want to use MKMapView to load the more accurate location with "mapView:didUpdateUserLocation":
Premise:
1.setup the mapView delegate.
2.setShowsUserLocation:YES
3.mapView must in a container(addSubview:mapView)!!!!!
For example:
self.mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
_mapView.delegate = self;
[_mapView setShowsUserLocation:YES];
[[UIApplication sharedApplication].keyWindow addSubview:_mapView];
Related
I want to get geotag location from image which is selected from image picker. I am using this code
if picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary
{
if let currentLat = pickedLat as CLLocationDegrees?
{
self.latitude = pickedLat!
self.longitude = pickedLong!
}
else
{
var library = ALAssetsLibrary()
library.enumerateGroupsWithTypes(ALAssetsGroupAll, usingBlock: { (group, stop) -> Void in
if (group != nil) {
println("Group is not nil")
println(group.valueForProperty(ALAssetsGroupPropertyName))
group.enumerateAssetsUsingBlock { (asset, index, stop) in
if asset != nil
{
if let location: CLLocation = asset.valueForProperty(ALAssetPropertyLocation) as CLLocation!
{ let lat = location.coordinate.latitude
let long = location.coordinate.longitude
self.latitude = lat
self.longitude = lat
println(lat)
println(long)
}
}
}
} else
{
println("The group is empty!")
}
})
{ (error) -> Void in
println("problem loading albums: \(error)")
}
}
}
i want to know to covert this code in swift 3 .I am new in coding with swift 3 .It will be very helpful
After hours of searching i got my ans
import UIKit
import Photos
class ViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var locationLabel: UILabel!
#IBOutlet weak var timeLabel: UILabel!
#IBOutlet weak var logi: UILabel!
#IBOutlet weak var lati: UILabel!
var lat = String()
var log = String()
var location = String()
var timeTaken = "Not Known"
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.
}
#IBAction func imagegeo(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var chosenImage:UIImage?
if let URL = info[UIImagePickerControllerReferenceURL] as? URL {
print("We got the URL as \(URL)")
let opts = PHFetchOptions()
opts.fetchLimit = 1
let assets = PHAsset.fetchAssets(withALAssetURLs: [URL], options: opts)
print(assets)
for assetIndex in 0..<assets.count {
let asset = assets[assetIndex]
location = String(describing: asset.location)
log = String(describing: asset.location?.coordinate.longitude)
lat = String(describing: asset.location?.coordinate.latitude)
timeTaken = (asset.creationDate?.description)!
print(log)
print(location)
print(lat)
}
}
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
chosenImage = editedImage
} else if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
chosenImage = selectedImage
}
dismiss(animated: true) {
DispatchQueue.main.async {
self.imageView.image = chosenImage
self.timeLabel.text = self.timeTaken
self.locationLabel.text = self.location
self.lati.text = self.lat
self.logi.text = self.log
}
}
}
}
I'm trying to find out how can i put an info bubble inside the annotation view when i click a pin on a map.
In the view did load I load this code that shows me the map
let latDelta:CLLocationDegrees = 0.01
let longDelta:CLLocationDegrees = 0.01
let evntLat : NSString = venueLat
let evntLng : NSString = venueLng
let latitute1:CLLocationDegrees = evntLat.doubleValue
let longitute2:CLLocationDegrees = evntLng.doubleValue
let theSpan:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
let pointLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitute1, longitute2)
let region:MKCoordinateRegion = MKCoordinateRegionMake(pointLocation, theSpan)
mappy.setRegion(region, animated: true)
let pinLocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitute1, longitute2)
let objectAnnotation = MKPointAnnotation()
objectAnnotation.coordinate = pinLocation
objectAnnotation.title = "\(self.venumeNam)"
self.mappy.addAnnotation(objectAnnotation)
Is there any way to put inside this annotation view a button?
I've tried this
let annotationView = MKAnnotationView()
let detailButton: UIButton = UIButton(type:UIButtonType.DetailDisclosure) as UIButton
annotationView.rightCalloutAccessoryView = detailButton
But i cant figure out how to implement it on my code so it can show it.
Any idea of how can i put this bubble and configure a function when someone clicks it?
FYI it's only one pin that i'm displaying here!
Updated from this answer
class detailsViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var mappy: MKMapView!
// Here we add disclosure button inside annotation window
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView{
print(view.annotation!.title) // annotation's title
print(view.annotation!.subtitle) // annotation's subttitle
//Perform a segue here to navigate to another viewcontroller
// On tapping the disclosure button you will get here
}
}
// Here we add disclosure button inside annotation window
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
print("viewForannotation")
if annotation is MKUserLocation {
//return nil
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
//println("Pinview was nil")
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.animatesDrop = true
}
let button = UIButton(type: .DetailDisclosure) as UIButton // button with info sign in it
pinView?.rightCalloutAccessoryView = button
return pinView
}
func displayMarkers() -> Void
{
let latDelta:CLLocationDegrees = 0.01
let longDelta:CLLocationDegrees = 0.01
let evntLat : NSString = venueLat
let evntLng : NSString = venueLng
let latitute1:CLLocationDegrees = evntLat.doubleValue
let longitute2:CLLocationDegrees = evntLng.doubleValue
let theSpan:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
let pointLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitute1, longitute2)
let annotationView = MKAnnotationView()
let region:MKCoordinateRegion = MKCoordinateRegionMake(pointLocation, theSpan)
mappy.setRegion(region, animated: true)
let pinLocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitute1, longitute2)
let objectAnnotation = MKPointAnnotation()
objectAnnotation.coordinate = pinLocation
objectAnnotation.title = "\(self.venumeNam)"
self.mappy.addAnnotation(objectAnnotation)
}
}
I have a TextView with some text, which font is Bold. And i´ve a button. When this button is tapped, the Bold Font should change to "UnBold"
There´s a ViewController & a class called "FontManager" to manage the Fonts of the TextKit/UITextView.
My code for the FontManager:
import UIKit
class FontManager {
var textView: UITextView! = nil
init(textView: UITextView) {
self.textView = textView
self.setFont()
}
// set a Range of the TextView to Bold at start:
func setFont() {
// set font to "HelveticaNeue"
let newFont = UIFont(name:"HelveticaNeue", size: textView.font!.pointSize)
self.textView.font = newFont
let range = NSMakeRange(11, 24)
self.makeBold(range)
}
// set attributes
func getDict(key : String, value: UIFont ) -> [String: AnyObject] {
return [key : value]
}
This code to set the Font to Bold in selectedRange works without problem
func makeBold(selectedRange: NSRange) {
self.addOrRemoveFontTraitWithName("Bold", andValue: UIFontDescriptorSymbolicTraits.TraitBold.rawValue, andRange:selectedRange)
}
func addOrRemoveFontTraitWithName(traitName: String, andValue traitValue: UInt32, andRange selectedRange: NSRange) {
let currentAttributesDict : NSDictionary! = self.textView.textStorage.attributesAtIndex(selectedRange.location, effectiveRange: nil)
let currentFont : UIFont = currentAttributesDict .objectForKey(NSFontAttributeName) as! UIFont
let fontDescriptor : UIFontDescriptor! = currentFont.fontDescriptor()
let fontNameAttribute : NSString = fontDescriptor.objectForKey(UIFontDescriptorNameAttribute) as! NSString
var existingTraitsWithNewTrait : UInt32! = nil
var changedFontDescriptor : UIFontDescriptor! = nil
Here is a check, if there is already bold text. If not (== NSNotFound) the text in selectedRange becomes the Bold "trait"
if fontNameAttribute.rangeOfString(traitName).location == NSNotFound {
existingTraitsWithNewTrait = fontDescriptor.symbolicTraits.rawValue | traitValue
changedFontDescriptor = fontDescriptor.fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits.TraitBold)
(1) if the Font in selectedRange is bold (else: != NSNotFound) the Font should be set to normal (UnBold)
} else {
existingTraitsWithNewTrait = fontDescriptor.symbolicTraits.rawValue & ~traitValue
changedFontDescriptor = fontDescriptor.fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits(rawValue: existingTraitsWithNewTrait))
}
let updatedFont = UIFont(descriptor:changedFontDescriptor, size: 0.0)
let dict = self.getDict(NSFontAttributeName, value: updatedFont)
self.textView.textStorage.beginEditing()
textView.textStorage.setAttributes(dict, range: selectedRange)
self.textView.textStorage.endEditing()
}
And now the Code of the ViewController:
class ViewController: UIViewController {
#IBOutlet weak var textView: UITextView!
var fontManger: FontManager! = nil
// the #IBAction to change the Font
#IBAction func SwitchFont(sender: AnyObject) {
let range = NSMakeRange(11, 24)
fontManger.makeBold(range)
}
#IBOutlet weak var textView: UITextView!
var fontManger: FontManager! = nil
override func viewDidLoad() {
super.viewDidLoad()
// init the FontManager
fontManger = FontManager(textView: self.textView)
}
At the first Tap of the button there should be a skip to (1), the else...
But this doesn´t happen. Can see that in debug mode???
Any idea is welcome!
download project
Found it! The Bold-Font is "HelveticaNeue-Bold". The "UnBold"-Font is "HelveticaNeue-Medium" but not "HelveticaNeue" and this difference is almost unvisible!
See no other way as adding
var updatedFont = UIFont(descriptor:changedFontDescriptor, size: 0.0)
if updatedFont.fontName == "HelveticaNeue-Medium" {
updatedFont = UIFont(name:"HelveticaNeue", size: textView.font!.pointSize)!
}
Or do u see a better solution?
hi I'm playing with the MPMoviePlayerController in swift
i have 2 MPMoviePlayerControllers I preload video in to each in view did load the second one plays from a button fine the first will play after the second has played? if I load the first one i get sound no picture but if play the second one then the first will then play fine?
here is a link to my testing
https://dl.dropboxusercontent.com/u/22927/videotest.zip
thanks for your help
import UIKit
import MediaPlayer
class ViewController: UIViewController
{
var moviePlayer : MPMoviePlayerController!
var moviePlayer2 : MPMoviePlayerController!
#IBOutlet weak var movieview: UIView!
#IBOutlet weak var movieview2: UIView!
override func viewDidLoad()
{
super.viewDidLoad()
loadMovie()
loadMovie2()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func play2(sender: AnyObject)
{
moviePlayer2.play()
}
#IBAction func playbtn(sender: AnyObject)
{
moviePlayer.play()
}
func loadMovie()
{
let path = NSBundle.mainBundle().pathForResource("video1", ofType:"mp4")
let url = NSURL.fileURLWithPath(path!)
moviePlayer = MPMoviePlayerController(contentURL: url)
moviePlayer.view.frame = CGRect(x: 0, y: 0, width: movieview.frame.size.width, height: movieview.frame.size.height )
moviePlayer.view.sizeToFit()
moviePlayer.scalingMode = MPMovieScalingMode.Fill
moviePlayer.fullscreen = false
moviePlayer.controlStyle = MPMovieControlStyle.None
moviePlayer.movieSourceType = MPMovieSourceType.File
moviePlayer.repeatMode = MPMovieRepeatMode.None
moviePlayer.prepareToPlay()
moviePlayer.pause()
movieview.addSubview( moviePlayer.view)
}
func loadMovie2()
{
let path = NSBundle.mainBundle().pathForResource("video2", ofType:"mp4")
let url = NSURL.fileURLWithPath(path!)
moviePlayer2 = MPMoviePlayerController(contentURL: url)
moviePlayer2.view.frame = CGRect(x: 0, y: 0, width: movieview2.frame.size.width, height: movieview2.frame.size.height )
moviePlayer2.view.sizeToFit()
moviePlayer2.scalingMode = MPMovieScalingMode.Fill
moviePlayer2.fullscreen = false
moviePlayer2.controlStyle = MPMovieControlStyle.None
moviePlayer2.movieSourceType = MPMovieSourceType.File
moviePlayer2.repeatMode = MPMovieRepeatMode.None
moviePlayer2.prepareToPlay()
moviePlayer2.pause()
movieview2.addSubview( moviePlayer2.view)
}
}
import UIKit
import AVFoundation
import AssetsLibrary
import MediaPlayer
import CoreMedia
var player : AVPlayer? = nil
var playerLayer : AVPlayerLayer? = nil
var asset : AVAsset? = nil
var playerItem: AVPlayerItem? = nil
var loadingAssetOne = false
#IBOutlet weak var movieview: UIView!
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func play2(sender: AnyObject)
{
loadingAssetOne = false
loadMovie()
}
#IBAction func playbtn(sender: AnyObject)
{
loadingAssetOne = true
loadMovie()
}
func loadMovie()
{
if loadingAssetOne
{
let path = NSBundle.mainBundle().pathForResource("video1", ofType:"mp4")
let url = NSURL.fileURLWithPath(path!)
asset = AVAsset(URL: url) as AVAsset
playerItem = AVPlayerItem(asset: asset!)
player = AVPlayer (playerItem: self.playerItem!)
playerLayer = AVPlayerLayer(player: self.player)
movieview.frame = CGRectMake(38, 57, 220, 106)
playerLayer?.frame = movieview.frame
movieview.layer.addSublayer(self.playerLayer!)
player!.play()
}
else
{
let path = NSBundle.mainBundle().pathForResource("video1", ofType:"mp4")
let url = NSURL.fileURLWithPath(path!)
asset = AVAsset(URL: url) as AVAsset
playerItem = AVPlayerItem(asset: asset!)
player = AVPlayer (playerItem: self.playerItem!)
playerLayer = AVPlayerLayer(player: self.player)
movieview.frame = CGRectMake(38, 206, 220, 106)
playerLayer?.frame = movieview.frame
movieview.layer.addSublayer(self.playerLayer!)
player!.play()
}
}
For more details,please go through the below source
Need to show multiple video using MPMoviePlayerController swift
I'm trying to build an application in Swift for OS X (With Xcode 6.1 GM) that is a MenuBar agent with a single window for preferences.
Though I've been able to get most of my menubar functionality working, it all exists in the AppDelegate and looks pretty messy.
import Cocoa
import AppKit
import Foundation
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var downloadClass = DownloadController()
#IBOutlet weak var window: NSWindow!
#IBOutlet weak var downloadButton: NSButton!
#IBOutlet weak var subredditField: NSTextField!
#IBOutlet weak var nsfwMarked: NSButton!
#IBOutlet weak var sortFilter: NSPopUpButton!
var statusBar = NSStatusBar.systemStatusBar()
var statusBarItem : NSStatusItem = NSStatusItem()
var menu: NSMenu = NSMenu()
var subSort: NSMenu = NSMenu()
override func awakeFromNib() {
//Add statusBarItem
statusBarItem = statusBar.statusItemWithLength(-1)
statusBarItem.menu = menu
let icon = NSImage(named: "arrow16black")
statusBarItem.image = icon
var downloadItem: NSMenuItem = NSMenuItem()
downloadItem.title = "Download"
downloadItem.action = Selector("downloadPressed:")
downloadItem.keyEquivalent = ""
menu.addItem(downloadItem)
var menuItem: NSMenuItem = NSMenuItem()
menuItem.title = "Preferences..."
//Open view on button click
menuItem.action = Selector("setWindowVisible:")
menuItem.keyEquivalent = ""
menu.addItem(menuItem)
//define sorting filters
let sortOptions = NSArray(array: ["Hot","New","Top","Rising","Controversial"])
sortFilter.addItemsWithTitles(sortOptions)
var sortItem: NSMenuItem = NSMenuItem()
sortItem.title = "Sort By"
menu.addItem(sortItem)
//Add sort options as submenu
for sort in sortOptions {
var item: NSMenuItem = NSMenuItem()
item.title = sort as String
item.keyEquivalent = ""
item.action = Selector("setActiveSort:")
subSort.addItem(item)
}
menu.setSubmenu(subSort, forItem: sortItem)
//Test receiving menu
let userDefaults = NSUserDefaults.standardUserDefaults()
if let filterDefault : AnyObject = userDefaults.objectForKey("filter") {
var active : NSString = filterDefault as NSString
sortFilter.selectItemWithTitle(active)
println(active)
subSort.itemWithTitle(active)?.state = 1
}
}
func setActiveSort(sender: NSMenuItem) {
//Turn off all other active filters
let allSorts = subSort.itemArray
var a = 0
while a < subSort.numberOfItems {
var filter = subSort.itemAtIndex(a)
filter?.state = 0
a++
}
//Make selected filter active and store value in Defaults
sender.state = 1
sortFilter.selectItemWithTitle(sender.title)
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(sender.title, forKey: "filter")
}
#IBAction func downloadPressed(sender: AnyObject) {
let subreddit: NSString = NSString(string: subredditField.stringValue)
let sortBy: NSString = NSString(string: sortFilter.titleOfSelectedItem!)
var sort = sortBy.lowercaseString
let nsfw: Bool = Bool(nsfwMarked.integerValue)
downloadClass.startController(subreddit, sortBy: sort, markNSFW: nsfw)
}
func setWindowVisible(sender: AnyObject) {
self.window!.orderFront(self)
}
func applicationDidFinishLaunching(aNotification: NSNotification?) {
// Insert code here to initialize your application
//Don't display application window at launch
self.window!.orderOut(self)
//On launch, get user preferences if set
let userDefaults = NSUserDefaults.standardUserDefaults()
if let nsfwMarkedPref : AnyObject = userDefaults.objectForKey("NSFW?") {
//Set nsfw state to stored value
nsfwMarked.state = (nsfwMarkedPref.integerValue == 1) ? NSOnState : NSOffState;
}
if let storedSubreddit : AnyObject = userDefaults.objectForKey("subreddit") {
//set subreddit string to stored value
subredditField.stringValue = storedSubreddit as String
}
//Get screen resolution
let ms = NSScreen.mainScreen()
let frame = ms?.frame
println(frame!.size.width)
}
func applicationWillTerminate(aNotification: NSNotification?) {
// Insert code here to tear down your application
//Set the user preferences on exit.. this should be moved to onButtonState
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(nsfwMarked.integerValue, forKey: "NSFW?")
let subreddit: NSString = NSString(string: subredditField.stringValue)
userDefaults.setObject(subreddit, forKey: "subreddit")
}
}
Currently, the IBAction of the downloadButton in my view will call the function within the DownloadController. But ideally I would like to be able to have the IBAction of downloadPressed right within the DownloadController.swift file, but I cannot seem to figure out how to go about this..
Thanks!
Create a XIB file or use storyboard and set it's file owner as your UI view controller. Then setup your actions and outlets there. I would recommend you watch some videos on you tube before you proceed.