I got an error [Type "View Controller" does not conform to protocol "ORKTaskViewControllerDelegate"] - researchkit

I am just starting to use swift3 in Xcode in order to utilize ResearchKit provided by Apple.inc.
Although I have worked through tutorials from Researchkit Tutorial with Swift: Getting started in Ray Wenderlich, I have a trouble in the extension of ViewController. The following is my code.
import ResearchKit
import UIKit
class ViewController: UIViewController {
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 consentTapped(sender : AnyObject) {
let taskViewController = ORKTaskViewController(task: ConsentTask, taskRun: nil)
taskViewController.delegate = self
present(taskViewController, animated: true, completion: nil)
}
}
extension ViewController: ORKTaskViewControllerDelegate {
func taskViewController(taskViewController: ORKTaskViewController, didFinishWithReason
reason: ORKTaskViewControllerFinishReason, error: NSError?) {
//Handle results with taskViewController.result
taskViewController.dismiss(animated:true, completion: nil)
}
}

You've missed to add delegate. Add ORKTaskViewControllerDelegate to ViewController
class ViewController: UIViewController,ORKTaskViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad(
}
}

Related

The files are grayed out in UIDocumentPicker

I’m unable to select the document documents they are greyed out
I have tried with
UIDocumentPickerViewController - each file that was picked once is then grayed out
import UIKit
import MobileCoreServices
import UniformTypeIdentifiers
class ViewController: UIViewController, UINavigationControllerDelegate, UIDocumentPickerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func ShowPicker(_ sender: Any) {
let pickerViewController = UIDocumentPickerViewController(forOpeningContentTypes: [.pdf], asCopy: true)
pickerViewController.delegate = self
pickerViewController.allowsMultipleSelection = false
pickerViewController.shouldShowFileExtensions = true
present(pickerViewController, animated: true, completion: nil)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
print("Cancelled")
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
print("didPickDocuments at \(urls)")
}
}

Unlapping optional error in UIView

I wanted to programmatically control the menu view so I tried the following:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var menuView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func menuBtn(_ sender: UIButton) {
print("menuBtn")
print(type(of: menuView!)) // <- `Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)`
}
}
And click the button, console says
fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)
Both are connected to ViewController.
How can I get print(type(of: menuView!))?
===============================================================
ps.
I've simplified my real problem. this is my real code:
button on ViewController.Swift
#IBAction func openModal(_ sender: UIButton) {
print("open btn clicked")
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "menuViewController") as! MenuViewController
self.addChildViewController(vc)
self.view.addSubview(vc.contentView!) /// <- This cause problem
}
MenuViewController.swift
import UIKit
class MenuViewController: UIViewController {
#IBOutlet weak var contentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clear
view.isOpaque = false
}
#IBAction func closeBtn(_ sender: UIButton) {
print("close btn clicked")
self.view.removeFromSuperview()
}
}
and Why I wan't using it:
I can't scrolling when menuView appeared.. I want to use the buttons in the menu view and scroll at the same time.

Search Google Places on tableView when textField is clicked in Swift 3?

How to Search Google Places when i click on textFieldand want to show results just below textField. I am using Swift 3.0 version.Could someone help me
First you need to install the GooglePlaces SDK in your project. Then you refer the code bellow.
in Swift 3
In AppDelegate
import UIKit
import CoreData
import GoogleMaps
import GooglePlacePicker
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
func setUpGoogleMaps()
return true
}
func setUpGoogleMaps() {
let googleMapsApiKey = "AIzaSyA-kiOBvrR9CNztqutwmKaSLyXIid93K0E"
GMSServices.provideAPIKey(googleMapsApiKey)
GMSPlacesClient.provideAPIKey("AIzaSyA-kiOBvrR9CNztqutwmKaSLyXIid93K0E")
}
In your ViewController which is having the textField
import UIKit
import GooglePlaces
import GoogleMaps
import GooglePlacePicker
class HotelVC: UIViewController, GMSMapViewDelegate, UITextFieldDelegate {
#IBOutlet weak var YourTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.YourTextField.delegate = self
}
func textFieldDidBeginEditing(_ textField: UITextField) {
let acController = GMSAutocompleteViewController()
acController.delegate = self
self.present(acController, animated: true, completion: nil)
}
}
extension viewController: GMSAutocompleteViewControllerDelegate {
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
print("Place name: \(place.name)")
print("Place address: \(place.formattedAddress ?? "null")")
self.YourTextField.text = place.formattedAddress
print("Place attributions: \(String(describing: place.attributions))")
self.dismiss(animated: true, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
// TODO: handle the error.
// print("Error: \(error.description)")
self.dismiss(animated: true, completion: nil)
}
// User canceled the operation.
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
print("Autocomplete was cancelled.")
self.dismiss(animated: true, completion: nil)
}
}
You will get location from the selected place. Try this code.
public func viewController(viewController: GMSAutocompleteViewController, didAutocompleteWithPlace place: GMSPlace) {
var lat = place.coordinate.latitude
var lon = place.coordinate.longitude
print("lat lon",lat,lon)
}

What can I do to fix this fatal error?

I'm completely new to API's, and am following this tutorial to implement Dropbox's API into an iPhone app I'm building. The tutorial was written in an earlier version of swift, so my problem could be an issue in translation. I'm pretty far along in the tutorial where it says that I should be able to run the app, but when I do, it crashes with a fatal error.
Here's the ViewController.swift code
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tblFiles: UITableView!
#IBOutlet weak var bbiConnect: UIBarButtonItem!
#IBOutlet weak var progressBar: UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tblFiles.delegate = self
tblFiles.dataSource = self
progressBar.isHidden = true
NotificationCenter.default.addObserver(self, selector: Selector(("handleDidLinkNotification:")), name: NSNotification.Name(rawValue: "didLinkToDropboxAccountNotification"), object: nil)
func handleDidLinkNotification(notification: NSNotification)
{
bbiConnect.title = "Disconnect"
}
if DBSession.shared().isLinked() {
bbiConnect.title = "Disconnect"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: IBAction method implementation
#IBAction func connectToDropbox(_ sender: AnyObject) {
if !DBSession.shared().isLinked() {
DBSession.shared().link(from: self)
}
else {
DBSession.shared().unlinkAll()
bbiConnect.title = "Connect"
}
}
#IBAction func performAction(_ sender: AnyObject) {
}
#IBAction func reloadFiles(_ sender: AnyObject) {
}
// MARK: UITableview method implementation
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 0.0
}
}
And the AppDelegate.swift code
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
#nonobjc func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let appKey = "XXXXX" // Set your own app key value here.
let appSecret = "XXXXX" // Set your own app secret value here.
let dropboxSession = DBSession(appKey: appKey, appSecret: appSecret, root: kDBRootAppFolder)
DBSession.setShared(dropboxSession)
return true
}
#nonobjc func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
if DBSession.shared().handleOpen(url as URL!) {
if DBSession.shared().isLinked() {
return true
}
}
return false
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
I'm out of my depth here. Thank you for your help!

Perform a segue to a new viewController when clicking the "use photo" button after taking picture with camera iOS 10 (swift 3)

I want the user to be taken to a new viewController after clicking "use photo" after taking a picture. However, the segue is never performed. I have attempted this segue by connecting two viewControllers via a manual segue. I have a print statement in my imagePickerController function which is where my segue code is. This print statement prints when I click "use photo", so why is my segue be ignored? I tried this exact same segue code within a "#IBAction func someButton (_sender: UIButton)" and it worked fine? Any help would be appreciated.
Here is my code:
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
#IBOutlet weak var imageTake: UIImageView!
var imagePicker: UIImagePickerController!
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 takePhoto(_ sender: UIButton) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
present(imagePicker, animated: true, completion: nil)
}
#IBAction func photoLib(_ sender: UIButton) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)
}
#IBAction func save(_ sender: AnyObject) {
UIImageWriteToSavedPhotosAlbum(imageTake.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
// we got back an error!
let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
} else {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
imagePicker.dismiss(animated: true, completion: nil)
imageTake.image = info[UIImagePickerControllerOriginalImage] as? UIImage
print("made it")
performSegue(withIdentifier: "new", sender: self)
}
}
Here's a suggestion. You have this:
imagePicker.dismiss(animated: true, completion: nil)
// ...
performSegue(withIdentifier: "new", sender: self)
Change it to this:
imagePicker.dismiss(animated: true, completion: {
performSegue(withIdentifier: "new", sender: self)
})
That way, we don't try to perform the segue until the image picker is in fact completely dismissed.
If that doesn't work, then I would have to conclude that there is no such segue as "new" coming from this view controller. But you have not shown your storyboard so I can't be certain.