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)
Related
If this seems like a dupe, sorry. I'm trying to ask a very specific question, and not sure my searching has really led me to the right place. Anyway, here's the setup. Take a picture on the iPhone camera, turn it into base64 string data, shove it up the wire to a Node API, turn that into a file to shove onto S3. Pretty straight forward.
General disclaimers apply; I'd prefer to use a B64 string in JSON for simplicity and universality, and I'll withhold further comments on the silliness of form-encoded uploads :)
Here's my very simple Swift code to produce B64, turn it back into an image, and display it as a proof that the stuff works - at least in Apple land.
Note: "redButton" is one of the assets in my app. I switched to that for the sake of sending much smaller packets at the API for testing, but the results remain. Thanks.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// build data packet
imagePicker.dismiss(animated: true, completion: nil)
//let image:UIImage = (info[UIImagePickerControllerOriginalImage] as? UIImage)!
let image:UIImage = UIImage(named: "redButton")!
showAlert( title: "size", msg: String( describing: image.size ) )
let data = UIImageJPEGRepresentation(image, 0.5)
let b64 = data!.base64EncodedData()//.base64EncodedString()//options: Data.Base64EncodingOptions.lineLength64Characters)
let b64String = b64.base64EncodedString()
debugPrint( "len=" + String( describing: b64String.lengthOfBytes(using: String.Encoding.utf8)))
let newDataString = Data.init(base64Encoded: b64String )
let newData = Data.init(base64Encoded: newDataString! )
let newImage = UIImage.init(data: newData!)
tmpImage.image = newImage
}
That all works. I see the image in the little UIImage.
So at least fully in the Apple camp, the img->b64->img works.
However...
When I copy the actual resulting blob of b64-encoded string data, and manually paste it into the source attribute, marked up with the data stuff, it does NOT display the expected image, and in fact, just shows a broken image in the browser.
ie...
<html>
<body>
<img src="data:image/jpg;base64,LzlqLzRBQVFTa1pKUmdBQkFRQUFTQUJJ (brevity)...">
</body>
</html>
So, am I doing something wrong in my proofing in the HTML page? Am I expecting the wrong results from what Apple calls base64 string data? Am I just plain missing something painfully obvious that my sleep-deprived brain is missing?
It eventually gets sent to the server in an HTTP POST call, per normal means, as a dictionary, turned into json via the json encoding stuff in newer Swift.
var params = ["image": [ "content_type": "image/jpg", "filename":"test.jpg", "file_data": b64String] ]
And for the sake of compeleteness, here's the Node code where I reconstitute this data into a binary bit, and from here I shove it up to the S3 system, and in every case, the file is not recognized as a proper JPG file.
var b64 = req.body.image.file_data;
var base64data = new Buffer(b64, 'base64'); // according to all the new-node version docs
I'm on the home stretch of a crunch-time product that we're shoving at investors next week, and apparently this is a critical feature to show off for that meeting.
Tell me I'm missing something painfully obvious, and that I'm stupid. I welcome it, please. It can't not be just something stupid, right?
Thanks!
Here:
let b64 = data!.base64EncodedData()
let b64String = b64.base64EncodedString()
you encode the given data twice. It should be just
let b64String = data!.base64EncodedString()
Your “in Apple land” test works because
let newDataString = Data.init(base64Encoded: b64String )
let newData = Data.init(base64Encoded: newDataString! )
also decodes the Base64 twice. That would now be just
let newData = Data(base64Encoded: b64String)
Im using Xcode 8.3 with Swift 3. I have written one method named pdfFromData(data:) to form the pdf document from the Data, whenever I build my project its not getting build due to this method, means the compiler is got stopped/hanged when it start compile particular file where I coded pdfFromData(data:) method(In Xcode 8.2 with Swift 3 it worked fine). Whenever i comment this method and build means everything working fine.
func pdfFromData(data: Data) -> CGPDFDocument? { // Form pdf document from the data.
if let pdfData = data as? CFData {
if let provider = CGDataProvider(data: pdfData) {
let pdfDocument = CGPDFDocument(provider)
return pdfDocument
}
}
return nil
}
What's wrong with this method?. I want to build my project with this method as well. Thanks in advance.
I tried debugging your issue. This is what I found out:
if let pdfData = data as? CFData {
}
The above line for casting object of type Data to CFData is where it's taking too much time to build.
Replacing that with the following piece of code significantly reduces your build time.
let pdfNsData: NSData = NSData(data: data) // convert `Data` to `NSData`
if let cfPdfData: CFData = pdfNsData as? CFData {
// cast `NSData` to `CFData`
}
NSData and CFData are toll-free bridged.
Please let me know if there's any doubt
I'm working on an horoscope application now I have a problem after user selected is zodiac how can I know what php url to show him for example:
there is 12 zodiac's so how can I give him his horoscope for this url for example
NSURL: "blablabla_horscope.com/libra/today_horoscope"
I mean I don't want to write in Xcode twelve options of url, and start making if statements for example "if this user and then use here is NSUserDefaults with his choosed zodiac"
since then I will have to start making a list of a lot of if statement and it will make my app work slow and it's a bad idea so I have thinking about making some kinda of php file, that will handle all that after the user registered in the background but where to start for that?
I'm currently working on Swift, core-data, php.
let urlString = "http://www.blablabla/?sign=libra&time=today"
let url = NSURL (string: urlString)
let dataURL = try? NSData(contentsOfURL: url!, options: [])
let result: String = String(data: dataURL!, encoding: NSUTF8StringEncoding)!
print("the result is %#", result)
Set your constant for the sign type prior to setting your urlString.
let sign = "libra"
or
let sign = "cancer"
etc...
and then you can:
let urlString = "http://www.blablabla/?sign=\(sign)&time=today"
Late
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
}
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.