elcimagepickercontroller in swift - swift

I am using xcode 7.2 and Swift 2.1.1. I am using ELCImagePickerController through bridging header. When I use ELCImagePickerControllerDelegate in class declaration,it shows error- the viewcontroller does not conform to protocol 'ELCImagePickerControllerDelegate'
let picker = ELCImagePickerController()
picker.maximumImagesCount = 5
picker.delegate = self
self.presentViewController(picker, animated: true, completion: nil)
This is my objective c header #import "ELCImagePickerController.h"
When I use this code on button click event it goes to empty view and not the gallery.Can anyone help me to overcome this error.
Thanks in advance.

Error - the viewcontroller does not conform to protocol 'ELCImagePickerControllerDelegate' because you have to implement below 2 delegate methods which are mandatory. ( Not optional )
func elcImagePickerController(picker: ELCImagePickerController!, didFinishPickingMediaWithInfo info: [AnyObject]!) {
}
func elcImagePickerControllerDidCancel(picker: ELCImagePickerController!) {
}
Download whole working project
Working code
import UIKit
class ViewController: UIViewController, ELCImagePickerControllerDelegate {
var picker = ELCImagePickerController(imagePicker: ())
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
picker.maximumImagesCount = 5
picker.imagePickerDelegate = self
self.presentViewController(picker, animated: true, completion: nil)
}
func elcImagePickerController(picker: ELCImagePickerController!, didFinishPickingMediaWithInfo info: [AnyObject]!) {
}
func elcImagePickerControllerDidCancel(picker: ELCImagePickerController!) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
That black screen were coming because of
var picker = ELCImagePickerController()
Proper way is
var picker = ELCImagePickerController(imagePicker: ())

Related

Get selected image in imagePickerController and pass it to coreML

I'm trying to do the recognition by using coreML, the function working and showing the result correctly. But I want to call the method into a button, like when I pressed the catDog button and it runs the method. But since the finalResult() and identifyCatOrDog() is its own function, so that I can't call it into the button. I tried to copy and paste the method inside the button, but it doesn't show me anything. How can I edit the code so that findResult() only work when I pressed the button not running automatically?
import UIKit
import CoreML
import Vision
import Photos
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet var loadImage: UIImageView!
#IBOutlet var Result: UILabel!
#IBAction func photoBtn(_ sender: UIButton) {
getPhoto()
}
#IBAction func cameraBtn(_ sender: UIButton) {
}
#IBAction func catDog(_ sender: UIButton) {
}
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.
}
func getPhoto() {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion: nil)
guard let gotImage = info[.originalImage] as? UIImage else {
fatalError("No picture chosen")
}
loadImage.image = gotImage
identifyCatOrDog(image: gotImage)
}
func identifyCatOrDog(image: UIImage) {
let modelFile = ImageClassifier()
let model = try! VNCoreMLModel(for: modelFile.model)
let handler = VNImageRequestHandler(cgImage: image.cgImage!, options: [ : ])
let request = VNCoreMLRequest(model: model, completionHandler: findResults)
try! handler.perform([request])
}
func findResults(request: VNRequest, error: Error?) {
guard let results = request.results as? [VNClassificationObservation] else {
fatalError("Unable to get results")
}
var bestGuess = ""
var bestConfidence: VNConfidence = 0
for classification in results {
if (classification.confidence > bestConfidence) {
bestConfidence = classification.confidence
bestGuess = classification.identifier
}
}
Result.text = "Image is: \(bestGuess) with confidence \(bestConfidence) out of 1"
}
I take it that the problem is that sometimes when the image picker is dismissed, you want to call identifyCatOrDog, but other times you don’t.
One rather crude possibility is this: In the button action method, raise a bool instance property flag so that when didFinishPickingMedia is called you know whether or not to call identifyCatOrDog.
A more sophisticated way would be to divide things off into helper classes so that the operation of the image picker after pressing the catDog button takes place within a completely different code world.

errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled"

I am trying to display or upload UIImage and I am getting this error.
"errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}"
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
// linked labels and UiButtons
#IBOutlet weak var ifix: UILabel!
#IBOutlet weak var UIImage: UIImageView!
let someImageView: UIImageView = {
let theImageView = UIImageView()
theImageView.translatesAutoresizingMaskIntoConstraints = false // call this property so the image is added to your view
return theImageView
}()
#IBAction func UploadImage(_ sender: UIButton) {
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerController.SourceType.photoLibrary
self.present(myPickerController, animated: true, completion: nil)
}
#objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any])
{
let image_data = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
let imageData:Data = image_data!.pngData()!
_ = imageData.base64EncodedString()
self.dismiss(animated: true, completion: nil)
}
#IBAction func UIShuffle(_ sender: UIButton) {
}
#IBAction func UIReset(_ sender: UIButton) {
}
override func viewDidLoad() {
super.viewDidLoad()
// additional setup after loading the view, typically from a nib.
view.addSubview(someImageView) //This add it the view controller without constraints
someImageViewConstraints() //This function is outside the viewDidLoad function that controls the constraints
}
// `.isActive = true` after every constraint
func someImageViewConstraints() {
someImageView.widthAnchor.constraint(equalToConstant: 180).isActive = true
someImageView.heightAnchor.constraint(equalToConstant: 180).isActive = true
someImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
someImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
}
}
This message is harmless. The message comes from the OS and is related to the OS keeping an eye out for any newly discovered extensions related to whatever your app is doing. I see it often on macOS when displaying an open file dialog. While browsing around for a file, the OS is checking to see if there are any file-related extensions it needs to load in order to show you something. When the user presses "OK" or "Cancel" it stops searching for the extensions and spits that message to the console. I gather iOS may be doing something similar, perhaps related to share or other user-file-related activities. The message does not indicate an error in your application.

Page View Controller viewDidLoad() Issues

I'm learning Swift/Xcode and trying to create an app with three pages that you can swipe back and forth using a Page View Controller. The issues I'm having lie in the UIViewController subclass, more specifically the viewDidLoad() function. I'm getting errors like "value of type 'NameOfMyClass' has no member datasource/delegate" and "use of unresolved identifier "setViewControllers". I've followed many tutorials and checked other posts but no one seems to be having these issues. When I attempted to run this I would get a black screen, and now I get a terminated due to signal 15 error.
Here's the relevant code where the errors are popping up:
import UIKit
class RootPageViewController: UIViewController,
UIPageViewControllerDataSource, UIPageViewControllerDelegate {
lazy var viewControllerList:[UIViewController] = {
return [self.VCInstance(name: "MissionOne"),
self.VCInstance(name: "MissionTwo"),
self.VCInstance(name: "MissionThree")]
}()
private func VCInstance(name: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle:
nil).instantiateViewController(withIdentifier: name)
}
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self //...has no member 'dataSource' error
self.delegate = self //...has no member 'delegate' error
if let MissionOne = viewControllerList.first {
setViewControllers([MissionOne], direction: .forward, animated:
true, completion: nil)
//use of unresolved indentifier 'setViewControllers' error
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
The other issue I'm having, and it may be related, is that the Page View Controller is not accepting/recognizing my class file to set as the custom class in the story board.
Thanks in advance for any insight or suggestions.
your RootPageViewController is subclass of UIViewController, not a UIPageViewController
I looks to me that you are mixing two different controllers here.
What you want to do is add 3 RootPageViewController to a UIPageViewController, yet here you are trying to add 3 RootPageViewControllers to a RootPageViewController!
One way to fix it is to have a RootPageViewController and a separate UIPageViewController which will contain all RootPageViewControllers like so:
// This is a UIPageViewController containing all RootPages
class PagesViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
lazy var viewControllerList:[UIViewController] = {
return [RootPageViewController.VCInstance(name: "MissionOne"),
RootPageViewController.VCInstance(name: "MissionTwo"),
RootPageViewController.VCInstance(name: "MissionThree")]
}()
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
if let MissionOne = viewControllerList.first {
setViewControllers([MissionOne], direction: .forward, animated:
true, completion: nil)
}
}
}
And the RootPageViewController which will be added in the UIPageViewController above:
// This is a UIViewController representing a single page
class RootPageViewController: UIViewController {
static func VCInstance(name: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: name)
}
// Do what you need a page to do...
}
With such a construction you will have all your errors solved and you will also be able to use PagesViewController as custom class in your Storyboard!

loadHTMLString and "thread 1 exc_bad_access (code=exc_i386_gpflt)"

Well, I'm not sure it is a real problem but it is unpleasant to see an error. The "thread 1 exc_bad_access (code=exc_i386_gpflt)" error appears with a probability of about 50% in simulator. But there is no error in real device.
I tried to use optionals, but without a noticeable result.
I have only WKWebView and a Button. The code is:
import UIKit
import WebKit
class ViewController: UIViewController {
#IBOutlet weak var WebView: WKWebView!
let all = ["kjhgjhkg","qqqqqqqqq", "wwwwwwwww", "lllllllll", "bbbbbbbb"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
WebView.loadHTMLString("<h1>The first title</h1>", baseURL: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func btnRefresh(_ sender: UIButton) {
let RandomNomber = Int(arc4random_uniform(UInt32(all.count)))
// let myString = all[RandomNomber]
// let myString2 = "<h1>" + myString + "</h1>"
WebView.loadHTMLString("<h1>" + all[RandomNomber] + "</h1>", baseURL: nil)
}
}

How to implement Interstitial iAds in Swift(Xcode 6.1)

I am trying to figure out how to switch over from my banner view iAds to interstitial iAds in order to free up space for a tabbed controller. For some reason I am completely unable to find any resource for even getting started on these ads with swift.
Could anyone please give me some information on interstitial iAds with Swift and how I can implement them in a project.
Here is a relatively cleaner and easier to follow way to implement Interstitial Ads since this way doesn't require the use of NSNotificationCentre
import UIKit
import iAd
class ViewController: UIViewController, ADInterstitialAdDelegate {
var interstitialAd:ADInterstitialAd!
var interstitialAdView: UIView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
loadInterstitialAd()
}
func loadInterstitialAd() {
interstitialAd = ADInterstitialAd()
interstitialAd.delegate = self
}
func interstitialAdWillLoad(interstitialAd: ADInterstitialAd!) {
}
func interstitialAdDidLoad(interstitialAd: ADInterstitialAd!) {
interstitialAdView = UIView()
interstitialAdView.frame = self.view.bounds
view.addSubview(interstitialAdView)
interstitialAd.presentInView(interstitialAdView)
UIViewController.prepareInterstitialAds()
}
func interstitialAdActionDidFinish(interstitialAd: ADInterstitialAd!) {
interstitialAdView.removeFromSuperview()
}
func interstitialAdActionShouldBegin(interstitialAd: ADInterstitialAd!, willLeaveApplication willLeave: Bool) -> Bool {
return true
}
func interstitialAd(interstitialAd: ADInterstitialAd!, didFailWithError error: NSError!) {
}
func interstitialAdDidUnload(interstitialAd: ADInterstitialAd!) {
interstitialAdView.removeFromSuperview()
}
And it may help if you put println("Function Name") in each function just to keep track of your Interstitial Ads process. If you have any questions and or a way to improve this block of code please leave a comment. Thank You
Here is how i use in my project
//adding iAd framework
import iAd
//conform iAd delegate
class ViewController: UIViewController,ADInterstitialAdDelegate
//create instance variable
var interstitial:ADInterstitialAd!
//default iAd interstitials does not provide close button so we need to create one manually
var placeHolderView:UIView!
var closeButton:UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//iAD interstitial
NSNotificationCenter.defaultCenter().addObserver(self, selector: ("runAd:"), name:UIApplicationWillEnterForegroundNotification, object: nil)
}
//iAD interstitial
func runAd(notification:NSNotification){
var timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: Selector("dislayiAdInterstitial"), userInfo: nil, repeats: false)
cycleInterstitial()
}
func cycleInterstitial(){
// Clean up the old interstitial...
// interstitial.delegate = nil;
// and create a new interstitial. We set the delegate so that we can be notified of when
interstitial = ADInterstitialAd()
interstitial.delegate = self;
}
func presentInterlude(){
// If the interstitial managed to load, then we'll present it now.
if (interstitial.loaded) {
placeHolderView = UIView(frame: self.view.frame)
self.view.addSubview(placeHolderView)
closeButton = UIButton(frame: CGRect(x: 270, y: 25, width: 25, height: 25))
closeButton.setBackgroundImage(UIImage(named: "error"), forState: UIControlState.Normal)
closeButton.addTarget(self, action: Selector("close"), forControlEvents: UIControlEvents.TouchDown)
self.view.addSubview(closeButton)
interstitial.presentInView(placeHolderView)
}
}
// iAd Delegate Mehtods
// When this method is invoked, the application should remove the view from the screen and tear it down.
// The content will be unloaded shortly after this method is called and no new content will be loaded in that view.
// This may occur either when the user dismisses the interstitial view via the dismiss button or
// if the content in the view has expired.
func interstitialAdDidUnload(interstitialAd: ADInterstitialAd!){
placeHolderView.removeFromSuperview()
closeButton.removeFromSuperview()
interstitial = nil
cycleInterstitial()
}
func interstitialAdActionDidFinish(_interstitialAd: ADInterstitialAd!){
placeHolderView.removeFromSuperview()
closeButton.removeFromSuperview()
interstitial = nil
println("called just before dismissing - action finished")
}
// This method will be invoked when an error has occurred attempting to get advertisement content.
// The ADError enum lists the possible error codes.
func interstitialAd(interstitialAd: ADInterstitialAd!,
didFailWithError error: NSError!){
cycleInterstitial()
}
//Load iAd interstitial
func dislayiAdInterstitial() {
//iAd interstitial
presentInterlude()
}
func close() {
placeHolderView.removeFromSuperview()
closeButton.removeFromSuperview()
interstitial = nil
}
I know this is old - but I just came across
override func prepareForSegue(segue: UIStoryboardSegue,
sender: AnyObject?) {
let destination = segue.destinationViewController
as UIViewController
destination.interstitialPresentationPolicy =
ADInterstitialPresentationPolicy.Automatic
}
If you add this to your app delegate, you'll avoid that 3 second delay suggested above.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIViewController.prepareInterstitialAds()
return true
}