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.
Related
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.
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.
}
}
import UIKit
import Metal
import QuartzCore
class ViewController: UIViewController {
var device: MTLDevice! = nil
var metalLayer: CAMetalLayer! = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
device = MTLCreateSystemDefaultDevice()
metalLayer = CAMetalLayer() // 1
metalLayer.device = device // 2
metalLayer.pixelFormat = .BGRA8Unorm // 3
metalLayer.framebufferOnly = true // 4
metalLayer.frame = view.layer.frame // 5
view.layer.addSublayer(metalLayer) // 6
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
When I have this in my ViewController.swift, I get the error "Use of undeclared type CAMetalLayer" even though I've imported Metal and QuartzCore. How can I get this code to work?
UPDATE:
Simulator support is coming this year (2019)
Pre Xcode 11/iOS 13:
Metal code doesn't compile on the Simulator. Try compiling for a device.
If your app has a fallback or mode that doesn't depend on Metal, and you want to compile your app for the simulator, you can do something like this:
#if targetEnvironment(simulator)
// dummy, do-nothing view controller for simulator
class ViewController: UIViewController {
}
#else
class ViewController: UIViewController {
var device: MTLDevice! = nil
var metalLayer: CAMetalLayer! = nil
override func viewDidLoad() {
super.viewDidLoad()
device = MTLCreateSystemDefaultDevice()
metalLayer = CAMetalLayer()
...
}
}
#endif
Then your code will at least compile for both device and simulator, which can ease your non-Metal development.
The same problem may appear if you name your XCode project "Metal".
In that case compiler will be confused and you'll receive the same error message.
I am new at ios development and I am trying to create an app in swift that will list all the files in the directory (all the files are PDF) and the user to be able to open them.
I have googling this for a the past two days and I am super confused. Can anyone suggest a tutorial or steps I would need to get this to work.
I have started with this in my ViewController.swift file:
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.
}
class func defaultManager()->NSFileManager{
}
}
I just don't know what to do next, very sad I know. I would appreciate any or all help.
Thanks,
J
let manager = NSFileManager.defaultManager()
var array = manager.contentsOfDirectoryAtPath(_ path: String,
error error: NSErrorPointer) -> [AnyObject]?
Swift 3.0 version
let manager = FileManager.default
let installed_files = try manager.contentsOfDirectory(atPath: "/Applications/")
Here is a more complete example and updated for Swift 2.
Add your files to a Folder (not a Group) in your project. Then use the following code to get a list of file names.
private func getListOfFileNames() -> Array<String> {
let docsPath = NSBundle.mainBundle().resourcePath! + "/DirectoryName"
let fileManager = NSFileManager.defaultManager()
let docsArray: Array<String>
do {
docsArray = try fileManager.contentsOfDirectoryAtPath(docsPath)
} catch {
print(error)
}
return docsArray
}
Maybe I am late to answer for you, but the answer may help others. I've found one library on github. This is a way to get access very easely to browse files. At here is example:
let fileBrowser = FileBrowser()
present(fileBrowser, animated: true, completion: nil)