WriteToFile not Working Swift - ios

I've been stuck with this problem for hours. I tried writing the class in Objective C, Swift, logging the output of the Array (Which is not nil and has no problems at all if logged), even using NSURL to use writeToFile. I cleaned the project and tested on iOS Simulator and on an iOS Device. This exact code works in a different class, but not in this one. Any help would be much appreciated...
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var docs: String = paths[0] as String
let responseData = docs.stringByAppendingPathComponent("myOwnData.plist")
let test = self.tweetsArray!.writeToFile(responseData, atomically: true)
println(test)

I tested the code with let array: NSArray = ["abc"] added at the beginning, and it worked.
OP solved it by adding self.tweetsArray = NSArray() at the top.

Related

AEXMLDocument loadXMLData() not working in Swift

I'm working with AEXML to write and read xml documents in Swift. I have the writing working no problem. And I have everything setup for the reading, but I can't seem to turn the saved text xml into the document object. It only ever gets the first element and none of the children. I've tried removing all the lines and spaces but still nothing. The content is reading into the String just fine and I've tried converting the data back to a string and it isn't getting messed up in conversion. Is this even possible with AEXML or am I just doing it wrong?
let doc = AEXMLDocument()
let content = try String(contentsOf:NSURL(string:file) as! URL)
let data = content.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let xml = NSString(data:data, encoding:String.Encoding.utf8.rawValue)
try doc.loadXMLData(data)
So I figured out that I was actually using an outdated version of AEXML which clearly wasn't working anymore. The updated code looks like this.
let content = try String(contentsOf:NSURL(string:file) as! URL)
let data = content.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let options = AEXMLOptions()
let doc = try AEXMLDocument(xml:data,options:options)

exc-bad-instruction code=i386_invop

I'm getting this error in latest version of xcode using swift 2
on line
let s = linkTxt.text
Text in linkTxt appears by button "pasteFromClipBoard"
let s = linkTxt.text
let u = NSURL(string: s!)
let file = u?.lastPathComponent
What is the reason of it and how to fix it?
Update:
the problem appears in function saveData() which calls when file downloading is finished. It calls from NSURLSessionDataTask function. More interesting, that in start-downloading-button there are the same lines where filename is generating and there is no such error on it. I fixed these issues by declaring variables, writing text's values into them and use these variables in saveData() except textObject.text; I had to delete lines with NSUserDefaults from saveData() too because I got the same error. Did understand nothing >_<
Update 2:
It's really a bug. I've deleted this line and wrote again - problem fixed
linkTxt.txt is returning nil and NSURL(string: s!) will try to forcefully unwrap it.
let s = linkTxt.text
if let s = linkTxt.txt {
let u = NSURL(string: s!)
let file = u?.lastPathComponent
}

Storing a dictionary in NSUserDefaults

I read a lot on Stack Overflow regarding this question, namely, Swift NSUserDefaults not saving Dictionary?, Saving dictionary into NSUserDefaults, and Store and update a Swift Dictionary in NSUserDefaults Xcode. However, I cannot seem to find a solution that works.
Someone graciously provided snippet of code that worked for him or her but it's not working for me and I'm not exactly sure why. Here is what I tried:
var addressDict = Dictionary<Int, Array<String>>()
addressDict[3] = ["string1", "string2"] //some example values
let data = NSKeyedArchiver.archivedDataWithRootObject(addressDict) //archiving
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(data, forKey: "address") //storing
if let data2 = defaults.objectForKey("address") as? NSData { //reading
let addressDict2 = NSKeyedUnarchiver.unarchiveObjectWithData(data2) //unarchiving
print(addressDict2)
}
I ran this snippet of code. And then I commented out addressDict[3] = ["string1", "string2"] and ran the application again. However, it seemed to be not saved onto memory since when this line of code executed print(addressDict2), there was no data in the dictionary. Anybody have a solution to solve this? Thank you in advance for your help! :)

Absolute paths of files in iOS applications in swift

I need to be able to reference a file which is stored in my Xcode project in the following way:
I want to be able to use files which I have stored inside of the "data" folder.
How do I reference it to be able to read its contents? What is it's directory path?
I just figured it out. The apple swift documentation and other developer references are really unclear about it.
The way you would reference the "data" folder so as to scan the entire contents is by writing the following:
let path = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("data")
var error: NSError?
let filesInDirectory: [String]! = fileManager.contentsOfDirectoryAtPath(path!, error: &error) as? [String]
This will return the contents of the files in the "data" folder as an array of filenames.
Hope this helps :)
Relative to swift 3
let bundleURL = Bundle.main.bundleURL
let dataFolderURL = bundleURL.appendingPathComponent("data")
let fileURL = dataFolderURL.appendingPathComponent("file.txt")
print(fileURL.path)
print(FileManager.default.fileExists(atPath: fileURL.path))
let bundleURL = NSBundle.mainBundle().bundleURL
let dataFolderURL = bundleURL.URLByAppendingPathComponent("data")
let fileURL = dataFolderURL.URLByAppendingPathComponent("fileName.txt")

'NSURLRequest?' does not have a member named 'URL' - Swift

Hi I am really new to coding in Swift, and am trying to follow the codes in this book: http://www.apress.com/9781484202098. Learn iOS 8 App Development 2nd Edition by James Bucanek
In particular, I am working through Chapter 3 - building a URL shortening app, but despite having copied the code exactly, I am getting an error on the code in Page 76:
if let toShorten = webView.request.URL.absoluteString {
which states 'NSURLRequest?' does not have a member named 'URL'.
I have tried googling an answer, but unfortunately have not come across anything. Any response I can find seems to suggest that my code ought to be working (e.g. How to get url which I hit on UIWebView?). This seems to have the closest answer SWIFT: Why I can't get the current URL loaded in UIWebView? but the solution does not appear to work for me. If I add a ? after the request, it will then at least build it, but I then have a nil variable returned.
I am using Xcode v6.1.1. Here is the piece of code that is coming up with the error in ViewController.swift:
let GoDaddyAccountKey = "0123456789abcdef0123456789abcdef" //this is replaced by my actual account key in my own code
var shortenURLConnection: NSURLConnection?
var shortURLData: NSMutableData?
#IBAction func shortenURL( AnyObject ) {
if let toShorten = webView.request?.URL.absoluteString { // ? now added
let encodedURL = toShorten.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let urlString = "http://api.x.co/Squeeze.svc/text/\(GoDaddyAccountKey)?url=\(encodedURL)"
shortURLData = NSMutableData()
if let firstrequest = NSURL(string: urlString) //added if here and removed !
let request = NSURLRequest(URL:firstrequest)
shortenURLConnection = NSURLConnection(request:request, delegate:self)
shortenButton.enabled = false
}
}
}
If you have any suggestions on how I can fix this, I would really appreciate it!
Update:
Following suggestions from Ashley below, I have amended my code so that it is no longer bringing up the error (see comments above). However, it is now no longer running. This appears to be because the urlString is being created as http://api.x.co/Squeeze.svc/text/d558979bb9b84eddb76d8c8dd9740ce3?url=Optional("http://www.apple.com/"). The problem is therefore the Optional() that is included and thus makes it an invalid URL. Does anyone have a suggestion on how to remove this please?
request is an optional property on UIWebView:
var request: NSURLRequest? { get }
also stringByAddingPercentEscapesUsingEncoding returns an optional:
func stringByAddingPercentEscapesUsingEncoding(_ encoding: UInt) -> String?
What you need is to make user of optional binding in a few places:
if let toShorten = webView.request?.URL.absoluteString {
if let encodedURL = toShorten.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
let urlString = "http://api.x.co/Squeeze.svc/text/\(GoDaddyAccountKey)?url=\(encodedURL)"
shortURLData = NSMutableData()
if let firstrequest = NSURL(string: urlString) { // If a method can return a nil, don't force unwrap it
let request = NSURLRequest(URL:first request)
shortenURLConnection = NSURLConnection(request:request, delegate:self)
shortenButton.enabled = false
}
}
}
See Apple's docs on optional chaining for details
See Apple's docs for NSURL class

Resources