Here is my Code!
I Have
iOS 11+,
swift 4+,
CoreBluetooth Framework
while I'm running my application it always shows Bluetooth is Off.but I run the same code in below iOS 10 version its runs how its happening?
My priority is to run on iOS 11+ what should I do? any suggestion???
import UIKit
import CoreBluetooth
class ViewController: UIViewController,CBCentralManagerDelegate {
var manager: CBCentralManager!
override func viewDidLoad() {
super.viewDidLoad()
manager = CBCentralManager(delegate: self, queue: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch (central.state) {
case .poweredOn:
print("bluetooth Powered ON")
case .poweredOff:
print("bluetooth Powered OFF")
case .unsupported:
print("bltyh noit supported")
case .unknown:
print("bltyh noit unknown")
case .resetting:
print("bltyh noit resetting")
case .unauthorized:
print("bltyh noit unauthorized")
}
}
}
Related
The error I am getting is the following.
Thread 1: "Unsupported object <CPInformationTemplate: 0x6000012de010> <identifier: 3444D3F1-ECFF-4953-B543-459286E11371, userInfo: (null), tabTitle: (null), tabImage: (null), showsTabBadge: 0> passed to setRootTemplate:animated:completion:. Allowed classes: {(\n CPTabBarTemplate,\n CPListTemplate,\n CPGridTemplate,\n CPAlertTemplate,\n CPVoiceControlTemplate,\n CPNowPlayingTemplate\n)}"
All I am trying to do so, far is show a simple basic text. - I am following https://adapptor.com.au/blog/enhance-existing-apps-with-carplay
Any suggestions would be helpful.
import Foundation
import CarPlay
class CarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegate {
func templateApplicationScene(_ templateApplicationScene: CPTemplateApplicationScene,
didConnect interfaceController: CPInterfaceController) {
if #available(iOS 14.0, *) {
let screen = CPInformationTemplate(title: "Root", layout: .leading, items: [CPInformationItem(title: "Hello", detail: "CarPlay")], actions: [])
interfaceController.setRootTemplate(screen, animated: true, completion: { _,_ in
// Do nothing
})
} else {
// Fallback on earlier versions
}
}
}
My AppDelegate is:
//
// AppDelegate.swift
// vscroll
//
// Created by Russell Harrower on 17/8/20.
// Copyright © 2020 Russell Harrower. All rights reserved.
//
import UIKit
import Flurry_iOS_SDK
import AVKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
MusicPlayer.shared.startBackgroundMusic(url:"https://api.drn1.com.au:9000/station/DRN1", type: "radio")
setupNotifications()
Flurry.startSession("GJV665GWWF25GPCD25W8", with: FlurrySessionBuilder
.init()
.withCrashReporting(true)
.withLogLevel(FlurryLogLevelAll))
return true
}
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
if(connectingSceneSession.role == UISceneSession.Role.carTemplateApplication) {
let scene = UISceneConfiguration(name: "CarPlay", sessionRole: connectingSceneSession.role)
// At the time of writing this blog post there seems to be a bug with the info.plist file where
// the delegateClass isn't set correctly. So we manually set it here.
if #available(iOS 14.0, *) {
scene.delegateClass = CarPlaySceneDelegate.self
} else {
// Fallback on earlier versions
}
return scene
} else {
let scene = UISceneConfiguration(name: "Phone", sessionRole: connectingSceneSession.role)
return scene
}
}
// MARK: UISceneSession Lifecycle
/* func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}*/
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
//CUSTOM CODE
func setupNotifications() {
// Get the default notification center instance.
let nc = NotificationCenter.default
nc.addObserver(self,
selector: #selector(handleInterruption),
name: AVAudioSession.interruptionNotification,
object: nil)
}
#objc func handleInterruption(notification: Notification) {
guard let userInfo = notification.userInfo,
let interruptionTypeRawValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
let interruptionType = AVAudioSession.InterruptionType(rawValue: interruptionTypeRawValue) else {
return
}
switch interruptionType {
case .began:
print("interruption began")
case .ended:
MusicPlayer.shared.player?.play()
print("interruption ended")
default:
print("UNKNOWN")
}
}
}
Which entitlements you have defined in your project? The templates availability depends on defined app entitlements.
Usage of the unsupported template (CPInformationTemplate) cause your error.
For example from documentation:
You can’t use CPInformationTemplate in apps with the audio
entitlement.
Hi I want to create a simple app when the app opens for the first time it will show other apple devices in my house that uses Bluetooth and it prints the device name. I am unsure how I can go about this using CoreBluetooth. I have tried a tutorial which i have put down below but it does not show the devices in my house and i have turned on bluetooth. It only shows my neighbour samsung tv. I was also wondering how i would a UUID so that i don't have repeated values in the console. I have even tried lightBlue app and it only show this samsung tv.
Code
import UIKit
import CoreBluetooth
class ViewController: UIViewController,CBCentralManagerDelegate {
private var centralManager : CBCentralManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
centralManager = CBCentralManager(delegate: self, queue: nil, options: nil)
view.backgroundColor = .white
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
print("Bluetooth is On")
centralManager.scanForPeripherals(withServices: nil, options: nil)
} else {
print("Bluetooth is not active")
}
}
public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
print("\nName : \(peripheral.name ?? "(No name)")")
print("RSSI : \(RSSI)")
for ad in advertisementData {
print("AD Data: \(ad)")
}
}
}
I recently decided to build an application using the Maps SDK from Google, but the problem is, when I open the view controller, it only let me click for the first item.
I cant find the solution using only the google documentation.
Anyone has a fix for this?
import UIKit
import GoogleMaps
import GooglePlaces
import GooglePlacePicker
class PlacePickerVC: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate, GMSAutocompleteViewControllerDelegate, UITextFieldDelegate {
let currentLocationMarker = GMSMarker()
var locationManager = CLLocationManager()
var local = ""
var morada = ""
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Teste"
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
let config = GMSPlacePickerConfig(viewport: nil)
let placePicker = GMSPlacePickerViewController(config: config)
placePicker.delegate = self
present(placePicker, animated: true, completion: nil)
}
// Handle the user's selection.
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
//Display the places but only show
print("Place name: \(place.name)")
print("Place address: \(place.formattedAddress)")
print("Place attributions: \(place.attributions)")
dismiss(animated: true, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
// TODO: handle the error.
print("Error: ", error.localizedDescription)
}
// User canceled the operation.
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
dismiss(animated: true, completion: nil)
}
}
extension PlacePickerVC : GMSPlacePickerViewControllerDelegate {
func placePicker(_ viewController: GMSPlacePickerViewController, didPick place: GMSPlace) {
print("Place name \(place.name)")
}
func placePicker(_ viewController: GMSPlacePickerViewController,
didFailWithError error: Error) {
// In your own app you should handle this better, but for the demo we are just going to log
// a message.
NSLog("An error occurred while picking a place: \(error)")
}
func placePickerDidCancel(_ viewController: GMSPlacePickerViewController) {
// Dismiss the place picker, as it cannot dismiss itself.
//viewController.dismiss(animated: true, completion: nil)
print("No place selected")
}
}
Numbers 1 2 and 3 can't be clicked.
i know this has been asked before but i'm trying to figure out the issue with my project, as the title states (a) is trying to present on (a) i have checked all segue triggers to see if i accidentally set a segue to go to the same view controller that it is already on but this is not the case.
view controller 1 code
import UIKit
import UserNotifications
class NotificationViewController: UIViewController {
let isRegisteredForRemoteNotifications = UIApplication.shared.isRegisteredForRemoteNotifications
let current = UNUserNotificationCenter.current()
#IBAction func Notification(_ sender: Any) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in})
var i = 0
while i < 1{
current.getNotificationSettings(completionHandler: { (settings) in
if settings.authorizationStatus == .notDetermined {
// Notification permission has not been asked yet, go for it!
}
if settings.authorizationStatus == .denied {
i = i + 1
DispatchQueue.main.async {
self.performSegue(withIdentifier: "ToLocation", sender: self)
// Notification permission was previously denied, go to settings & privacy to re-enable
}
}
if settings.authorizationStatus == .authorized {
i = i + 1
DispatchQueue.main.async {
self.performSegue(withIdentifier: "ToLocation", sender: self)
// Notification permission was already granted
}
}
})
}
}
override func viewDidLoad() {
current.getNotificationSettings(completionHandler: { (settings) in
if settings.authorizationStatus == .notDetermined {
// Notification permission has not been asked yet, go for it!
}
if settings.authorizationStatus == .denied {
DispatchQueue.main.async {
self.performSegue(withIdentifier: "ToLocation", sender: self)
// Notification permission was previously denied, go to settings & privacy to re-enable
}
}
if settings.authorizationStatus == .authorized {
DispatchQueue.main.async {
self.performSegue(withIdentifier: "ToLocation", sender: self)
// Notification permission was already granted
}
}
})
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.
}
}
view controller 2 code
import UIKit
import CoreLocation
class LocationViewController: UIViewController {
#IBOutlet weak var textview: UITextView!
let locationManager = CLLocationManager()
#IBAction func OnLocation(_ sender: Any) {
locationManager.delegate = self as? CLLocationManagerDelegate
var i = 0
while i < 1{
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
// Request when-in-use authorization initially
locationManager.requestWhenInUseAuthorization()
break
case .restricted, .denied:
i = i + 1
DispatchQueue.main.async {
self.performSegue(withIdentifier: "ToLogin", sender: self)
}
// Disable location features
//disableMyLocationBasedFeatures()
break
case .authorizedWhenInUse:
i = i + 1
DispatchQueue.main.async {
self.performSegue(withIdentifier: "ToLogin", sender: self)
}
// Enable basic location features
//enableMyWhenInUseFeatures()
break
case .authorizedAlways:
// Enable any of your app's location features
// enableMyAlwaysFeatures()
break
}
}
}
override func viewDidLoad() {
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) { switch status {
case .restricted, .denied:
self.performSegue(withIdentifier: "ToLogin", sender: self)
break
case .authorizedWhenInUse:
self.performSegue(withIdentifier: "ToLogin", sender: self)
break
case .authorizedAlways:
self.performSegue(withIdentifier: "ToLogin", sender: self)
break
case .notDetermined:
break
}
}
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
error message
018-02-27 23:06:41.534749+1030 Request[27358:1351259] Warning: Attempt
to present on
while a presentation
is in progress!
No no no no no. This is not the way. sorry about this plenty of no´s but completionHandler result parameter of the requestAuthorization method from UNUserNotification may be executed on a background thread.
tips for this function
#IBAction func Notification(_ sender: Any)
*should start with lowercase
*provide a name that the action it accomplish can be inferred by that name
*change the type of the sender (if you know it), that way you can explicitly call properties or methods on that object without cast.
continuing with the rest of the code inside the scope of the function. requestAuthorization have the only responsibility of that - ask for a permission - and the response is didAllow or error. You never check this and continue launching another block that response is also another thread
bottom line: your calling requestAuthorization and then getNotificationSettings inside a loop (why?), you have a lot of luck if this code execute 30% of the time.
So you should separate some of the code involving permissions, read some lines about GRASP principle, also read every chapter here
Your error message is pretty clear while a presentation is in progress. That mean that you try to present LocationViewController from another LocationViewController, but it still not presented yet.
Move your presentation logic to viewWillAppear method. It will help
UPDATE
1) remove your existing segue from Notification button to LocationViewController in storyboard
2) Add segue from NotificationViewController to LocationViewController like it shown on picture
3) Set name for this segue
Now try to run your project
I am using iOS SDK 8.1 trying to call requestWhenInUseAuthorization() method to prompt user to grant access to my app. I imported CoreLocation.framework, and added NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription keys into info.plist. When I ran the app, it never prompted me for location access. Below is my code, what have I missed?
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
var manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
let authorizationStatus = CLLocationManager.authorizationStatus()
switch authorizationStatus {
case .Authorized:
println("authorized")
case .AuthorizedWhenInUse:
println("authorized when in use")
case .Denied:
println("denied")
case .NotDetermined:
println("not determined")
case .Restricted:
println("restricted")
}
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let location = locations[0] as CLLocation
println("Latitude: \(location.coordinate.latitude). Longitude: \(location.coordinate.longitude).")
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .Authorized:
println("authorized")
case .AuthorizedWhenInUse:
println("authorized when in use")
case .Denied:
println("denied")
case .NotDetermined:
println("not determined")
case .Restricted:
println("restricted")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
The console only showed "not determined" once and nothing else. So I went to iPhone Simulator => Settings => Privacy => Location => My App. It showed me 3 options: "Never", "While Using the App", "Always". But nothing was selected.
Problem solved. My manager was declared as local var inside viewDidLoad() method, but it should've been a class level property.
After I moved manager declaration out of viewDidLoad(), my app worked.
Not sure how exactly manager.requestWhenInUseAuthorization() work behind the scene and why exactly manager defined within viewDidLoad() not work. Hope someone who knows this detail enlighten me.
Setting these properties in the viewWillAppear instead of the viewDidLoad fixed it for me, thanks!
override func viewWillAppear(animated: Bool) {
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
I also faced the same problem. I have added two keys together in info.plist.
NSLocationWhenInUseUsageDescription key is supported in iOS 8.0 and later. If your Info.plist file includes both this key and the NSLocationUsageDescription key, the system uses this key and ignores the NSLocationUsageDescription key.
Rearranged the code:
let locationManager: CLLocationManager = CLLocationManager()
let authorizationStatus = CLLocationManager.authorizationStatus()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
if(authorizationStatus == .Denied)
{
print("DENIED")
locationManager.requestWhenInUseAuthorization()
}
}
override func viewWillAppear(animated: Bool) {
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
Clean the project and run again.