Here is an simple Swifter application in Swift 3.2 and xCode9.
Its working.
But I would write this application when this app is in background, then it bringing to front and I will see the standard white screen.
What is the best way for this idea?
import UIKit
import AudioToolbox
import WatchKit
import Foundation
import Swifter
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let server = HttpServer()
server["/hello"] = {
var queryParamsInfo = ""
for (name, value) in $0.queryParams {
queryParamsInfo += "\(name) -> \(value)<br/>"
}
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
return .ok(.html("<h3>You asked for \(queryParamsInfo)</h3>"))
}
do {
try server.start()
print("Server is started")
while true {
}
}
catch {
print("Error!")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Thanks for your help!
This is not possible on iOS. An application can only enter the foreground if
The user taps the app icon
The user taps a notification
The user brings the app to the foreground from the multitasking menu
The app is opened by another app (using URL Schemes)
You can not bring your app to the foreground programatically.
Related
Im trying to play a Youtube video in my app with the Webview
the build is succsesful but when i run the app it shows all white and i get this error: Thread 1:EXC_BAD_INSTRUCTION(code=EXC_I1386_INVOP,subcode=0x0)
it happenes on the Youtube.loadRequest(URLRequest(url:url!))
//
// ViewController.swift
// CFBC
//
// Created by KWIA on 6/6/17.
// Copyright © 2017 KWIA. All rights reserved.
//
import UIKit
import Firebase
class ViewController: UIViewController {
#IBOutlet weak var Youtube: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
getVideo(videoCode: "RmHqOSrkZnk")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getVideo(videoCode:String)
{
let url = URL(string: "https//www.youtube.com/embed/\(videoCode)")
Youtube.loadRequest(URLRequest(url: url!))
}
}
Your URL is not valid, you are missing : after https.
It should be: "https://www.youtube.com/embed/\(videoCode)"
That leads to URL(string:) returning nil and to a crash when you try to force unwrap it using !.
I've been trying to connect my postgreSQL database to an iOS app on swift for quite a while now. I managed to connect it for macOS development by creating Obj-C Bridging header for system provided libpq framework, but macOS development is unusual for me and I want this project to be done well. I found a libpq framework for iOS Obj-C, tried to access it through Bridging Header, but server is not responding to my queries.
I put this within my bridging header
#import <libpq/libpq-fe.h>
And this is my view controller code
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let conn = PQconnectdb("postgresql://localhost/investProject".cString(using: .utf8))
if PQstatus(conn) == CONNECTION_OK {
let result = PQexec(conn, "SELECT version()")
for i in 0 ..< PQntuples(result) {
guard let value = PQgetvalue(result, i, 0) else { continue }
let dbname = String(cString: value)
print(dbname)
}
PQclear(result)
}
PQfinish(conn)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Compiler recognizes all the methods, output is supposed to be the version of my db, but it's empty instead.
Between the pod spec and what is currently on S.O. I had a tough time figuring out how to get speech-to-text working using SpeechKit + CocoaPod + Swift. Finally got it working so figured I'd help the next poor soul that comes looking for help! :)
First install the CocoaPod: https://cocoapods.org/pods/SpeechKit
Add #import <SpeechKit/SpeechKit.h> to your bridging header
Login to Nuance's dev portal and create an app: https://developer.nuance.com/
Clean up the demo code so that is is more organized. I just wanted as much of the code to be in one place as possible so you can see a fully working implementation.
Then create a UIViewController and add the following code with the correct credentials:
import UIKit
import SpeechKit
class SpeechKitDemo: UIViewController, SKTransactionDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//!!link this to a corresponding button on the UIViewController in I.B.
#IBAction func tappedButton(sender: AnyObject) {
// All fields are required.
// Your credentials can be found in your Nuance Developers portal, under "Manage My Apps".
let SKSAppKey = "[Get this from the nuance app info page]";
let SKSAppId = "[Get this from the nuance app info page]";
let SKSServerHost = "[Get this from the nuance app info page]";
let SKSServerPort = "[Get this from the nuance app info page]";
let SKSLanguage = "eng-USA";
let SKSServerUrl = "nmsps://\(SKSAppId)#\(SKSServerHost):\(SKSServerPort)"
let session = SKSession(URL: NSURL(string: SKSServerUrl), appToken: SKSAppKey)
//this starts a transaction that listens for voice input
let transaction = session.recognizeWithType(SKTransactionSpeechTypeDictation,
detection: .Short,
language: SKSLanguage,
delegate: self)
print(transaction)
}
//required delegate methods
func transactionDidBeginRecording(transaction: SKTransaction!) { }
func transactionDidFinishRecording(transaction: SKTransaction!) { }
func transaction(transaction: SKTransaction!, didReceiveRecognition recognition: SKRecognition!) {
//Take the best result
let topRecognitionText = recognition.text;
print("Best rec test: \(topRecognitionText)")
//Or iterate through the NBest list
let nBest = recognition.details;
for phrase in (nBest as! [SKRecognizedPhrase]!) {
let text = phrase.text;
let confidence = phrase.confidence;
print("\(confidence): \(text)")
}
}
func transaction(transaction: SKTransaction!, didReceiveServiceResponse response: [NSObject : AnyObject]!) { }
func transaction(transaction: SKTransaction!, didFinishWithSuggestion suggestion: String!) { }
func transaction(transaction: SKTransaction!, didFailWithError error: NSError!, suggestion: String!) { }
}
Learning swift 2/ Xcode 7 and creating a app iOS 9 where I can enter a custom address. I have mapkit working and can search regular address. I have my current location working. Instead of entering an address: "Number,Street, city, zip code", I want the user to enter: PR33.1 for example, and that would show the user that location. I have the long and lats for the custom address's, I've read many things on geocoding and annotations but nothing that would let me accomplish what I need. Can this be done? jSon file maybe.. I'm really new at this...
thanks
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
let arbitraryString: [String:String] =
["161 RL2": "23908709138882,-106.7433588579297",
"40.9 RL112":"32.393144,-106.727762"]
#IBAction func enterButtonTapped(sender: AnyObject) {
if let textField = arbitraryString["161 RL2"] {
print(" \(textField).")
} else {
print("That is not in the dictionary.")
}
}
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.
}
}
I'm trying to use Pusher for my iOS app. I installed Starscream.framework into my app as client side. I was able to connect to the specific Pusher's app. And also I was able to disconnect it by tapping a button on my app. I can watch these activities and logs from Debug Console of Pusher.
But, if I create new event from Debug Console, my iOS app doesn't receive it event."websocketDidReceiveMessage" function will not work. Image of Debug Console
I think that I made mistake. Please tell me if there is some kind of mistake.
Best regards.
Here is my code.
import UIKit
import Parse
import Starscream
class ViewController: UIViewController, WebSocketDelegate {
var socket = WebSocket(url: NSURL(scheme: "ws", host: "ws.pusherapp.com/app/API_KEY?protocol=7", path: "/")!)
override func viewDidLoad() {
super.viewDidLoad()
self.socket.delegate = self
self.socket.connect()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func disconnectWasTapped(sender: UIButton) {
self.socket.disconnect()
}
// MARK: WebSocket
func websocketDidConnect(socket: WebSocket) {
println("websocket is connected")
}
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
println("websocket is disconnected: \(error?.localizedDescription)")
}
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
//println("got some text!!")
println("got some text: \(text)")
}
func websocketDidReceiveData(socket: WebSocket, data: NSData) {
println("got some data: \(data.length)")
}
}
UPDATE
I was able to fix my problem by my self. I decided not to use Pusher. I decided to use PubNub instead Pusher. It is working on Swift now. And it is really easy to integrate with Parse to realize the realtime communication.