use of unresolved identifier in swift with ubuntu 14.04 - swift

honestly i am a noob in swift, but i have a project to do with this language, so, here is the code:
import Foundation
//let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as? [String];
//let dir = dirs![0];
var dir = "/home/guillermo/Escritorio/";
var file = "tokens";
var path = dir.stringByAppendingPathComponent(file);
if let archivoTokens = try? NSString(contentsOfFile: path as String, encoding: NSUTF8StringEncoding){
print(archivoTokens)
}
var lineasArchivoTokens:[String] = archivoTokens!.componentsSeparatedByString("\n");
var TOKENS:[String] = [String]();
var count = lineasArchivoTokens.count;
for index in 0..<count{
var tmpList:[String] = (lineasArchivoTokens[index]).componentsSeparatedByString(" ");
}
and this is the error:
error: use of unresolved identifier 'archivoTokens'
var lineasArchivoTokens = archivoTokens!.componentsSeparatedByString("\n");

As #thefredelement said, you cannot use archivoTokens outside the if let archivoTokens = ... { ... } block.
You can reflow your code like this:
if let archivoTokens = try? NSString(contentsOfFile: path as String, encoding: NSUTF8StringEncoding){
// note that archivoTokens here is not an Optional because it is garenteed not to be nil
// so the ! suffix is not needed
print(archivoTokens)
var lineasArchivoTokens:[String] = archivoTokens.componentsSeparatedByString("\n")
}
Or, in a more natural way, use guard:
guard let archivoTokens = try? NSString(contentsOfFile: path as String, encoding: NSUTF8StringEncoding) else {
// guard statement requires exit when condition not satisfied
// you can also use `return` if it's inside a function
fatalError("failed to read archivoTokens from file")
}
// now archivoTokens is a normal non-nil NSString
var lineasArchivoTokens:[String] = archivoTokens.componentsSeparatedByString("\n");
var TOKENS:[String] = [String]();
var count = lineasArchivoTokens.count;
for index in 0..<count{
var tmpList:[String] = (lineasArchivoTokens[index]).componentsSeparatedByString(" ");
}

Related

Swift macOS - find all files of a specific extension

I need to find the names of all files that have the extension .pub in the path ~/.ssh.
So in the end I need to have an array of names.
I solved it like this, I wonder if there is a possibility to write it in a better and more compact way as code.
func arrayFile(path: String, ext: String) -> [String] {
guard let desktopPath = NSSearchPathForDirectoriesInDomains(.desktopDirectory,.userDomainMask,true).first else { return [] }
let pathConfig = desktopPath.replacingOccurrences(of: "Desktop", with: path)
let filemanager: FileManager = FileManager()
let files = filemanager.enumerator(atPath: pathConfig)
var array = [String]()
while let file = files?.nextObject() as? String {
if file.hasSuffix(ext) {
let name = file.replacingOccurrences(of: ext, with: "")
array.append(name)
}
}
return array
}
let array = arrayFile(path: ".ssh/", ext: ".pub")
print(array)
Can you give me some suggestions?

Swift - Why is my JSON object element only adding the last array element?

I have a problem with my JSON object. Everything is working fine creating and printing out my JSON object, apart from the idQty part. It only prints the last key value result. I assume I have a problem with my for loop. If anybody can point out where I've went wrong, it would be of huge help.
Code below:
struct Order: Codable {
let idQty: [IdQty]
let collection: String
let name: String
let phone: Int
let doorNum: Int
let street: String
let postcode: String
}
struct IdQty: Codable {
let itemId: Int
let qty: Int
}
class CheckoutServer: NSObject, URLSessionDataDelegate {
var inputVals = [Int:Int]()
var idQty = [IdQty]()
var collection = String()
var name = String()
var phone = Int()
var doorNum = Int()
var street = String()
var postcode = String()
var request = URLRequest(url: NSURL(string: "http://192.168.1.100/api/AddOrder.php")! as URL)
func downloadItems() {
for(key,value) in inputVals {
idQty = [IdQty(itemId: key,qty: value)]
}
let order = Order(idQty: idQty,collection: collection,name: name,phone: phone,doorNum: doorNum,street: street,postcode: postcode)
let encodedOrder = try? JSONEncoder().encode(order)
var json: Any?
request.httpMethod = "POST"
if let data = encodedOrder {
json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
if let json = json {
}
}
let postParameters = "json="+String(describing: json!)
request.httpBody = postParameters.data(using: .utf8)
print(String(describing: json!))
let defaultSession = URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: request) { (data, response, error) in
if error != nil {
print("Failed to upload data at Menu Type Items")
} else {
print("Data uploaded")
}
}
task.resume()
}
}
Below is the output. the 'idQty' part only ever returns the last entry in the [Int:Int] dictionary:
{
collection = Delivery;
doorNum = 4;
idQty = (
{
itemId = 14;
qty = 2;
}
);
name = James;
phone = 4355345;
postcode = Test;
street = TestStreet;
}
You should append new value to your array instead of recreating it on each iteration
for(key,value) in inputVals
{
idQty.append(IdQty(itemId: key,qty: value))
}

Convert string to base64 in Swift 3

let strsize = 10_000_000
let tries = 100
var longstring:String = "a"
for i in 1...strsize {
longstring += "a"
}
for i in 1..<2 {
let basestring = NSData(base64EncodedString: longstring, options: .IgnoreUnknownCharacters)
print(basestring)
}
Writing a code in command prompt. What is the correct code to write for Swift 3 which I been getting use of unresolved identifier NSData . Most of the tutorials on encoding string to base64 aren't working.
This is working for you on Linux or Mac?
http://studyswift.blogspot.sg/2016/03/convert-nsdatauint8-to-base64-in-swift.html
Use this instead:
let longstring = "test123"
if let data = (longstring).data(using: String.Encoding.utf8) {
let base64 = data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
print(base64)// dGVzdDEyMw==\n
}
this string extention can help .
extension String {
//Base64 decode
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return String(data: data, encoding: .utf8)
}
//Base64 encode
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
}
how to use.
let str = "Hello World"
str.toBase64().fromBase64()
In Swift 4.2 and Xcode 10.1
//Base64 encoding
let data = combinedString.data(using: .utf8)//Here combinedString is your string
let encodingString = data?.base64EncodedString()
print(encodingString!)
// OR Single line of code
let encodingString = combinedString.data(using: .utf8)?.base64EncodedString()//Here combinedString is your string
print(encodingString!)

Swift Save images (screenshots) to nsuserdefaults

I have a program, where the user "creates" an image, and then the program takes a screenshot of the screen. I would then like to save this screenshot to a database, prefferebly nsuserdefaults, since I am accessing it later in a table view. Any other suggestions on how to approach this, are more than welcome :)
The code is like this
let screenshot = getScreenshot() // saves the screenshot
var imagePaths = [String]()
// get the array of previous screenshots
if let _ = NSUserDefaults.standardUserDefaults().objectForKey(theKey)
{
imagePaths = NSUserDefaults.standardDefaults().objectForKey(theKey) as! [String]
}
// then I want to get a path to the image something like
let imagePath = screenshot.getPath() // although this is not a valid method, this is basically what I want
// add the imagePath
imagePaths.append(imagePath)
// finally I save the image
NSUserDefaults.standardUserDefaults().setObject(imagePaths, forKey: theKey)
You can create directory in Documents and save there screenshots as usual files. Filename can be generated from date and time for uniqueness.
func saveImage(imageData: NSData)
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy hh.mm.ss"
let filename = "\(dateFormatter.stringFromDate(NSDate())).png"
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
let imagesDirectory = documentsDirectory.stringByAppendingPathComponent("Images")
let filePath = imagesDirectory.stringByAppendingPathComponent(filename)
if !NSFileManager.defaultManager().fileExistsAtPath(imagesDirectory)
{
var error: NSError?
NSFileManager.defaultManager().createDirectoryAtPath(imagesDirectory, withIntermediateDirectories: false, attributes: nil, error: &error)
if error != nil
{
println("\(error!.localizedDescription)")
return
}
}
imageData.writeToFile(filePath, atomically: true)
}
func getImagesPaths() -> [String]?
{
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
let imagesDirectory = documentsDirectory.stringByAppendingPathComponent("Images")
if let filenames = NSFileManager.defaultManager().contentsOfDirectoryAtPath(imagesDirectory, error: nil)
{
let imagePaths = filenames.map{"\(imagesDirectory)/\($0)"}.filter(){$0.pathExtension == "png"}
return imagePaths.count > 0 ? imagePaths : nil
}
return nil
}
To save image simply use saveImage(data). To get images paths use getImagesPaths().
If you need array of UIImage, you can get it by follow way:
var images : [UIImage] = [ ]
if let imagePaths = getImagesPaths()
{
for path in imagePaths
{
if let image = UIImage(contentsOfFile: path)
{
images.append(image)
}
}
}

Check file exists in directory with prefix of file name in Swift

I want to check whether my File is exist with just prefix of file name in SWIFT.
E.g
My file name is like Companies_12344
So after _ values are dynamic but "Companies_" is static.
How can i do that?
I have already done split filename code below
How can i check through NSFileManager for is exist file name with "Companies_"
My code below For split
func splitFilename(str: String) -> (name: String, ext: String)? {
if let rDotIdx = find(reverse(str), "_")
{
let dotIdx = advance(str.endIndex, -rDotIdx)
let fname = str[str.startIndex..<advance(dotIdx, -1)]
println("splitFilename >> Split File Name >>\(fname)")
}
return nil
}
I think this code you need:
let str = "Companies_12344"
if str.hasPrefix("Companies") {
println("Yes, this one has 'Companies' as a prefix")
let compos = str.componentsSeparatedByString("_")
if let file = compos.first {
println("There was a code after the prefix: \(file)")
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
var yourPath = paths.stringByAppendingPathComponent("\(file)_")
var checkValidation = NSFileManager.defaultManager()
if (checkValidation.fileExistsAtPath(yourPath))
{
println("FILE AVAILABLE");
}
else
{
println("FILE NOT AVAILABLE");
}
}
}