I have a json object like thies {"test" : "test"}, but if I convert it to a SwfiftyJSON.JSON object, and then I fetch the rawstring by function rawString(), then I convert the rawstring to a json object, but unfortunately, I can not get the correct json object, if I try to get "test" property or any other property, it always return nil, what is wrong?
SWIFT 5
If you want to get rid of white-spaces and new lines characters from your output, you should disable pretty Printing.
You can achieve this by
let myString = yourJsonObject.rawString(String.Encoding.utf8, options: JSONSerialization.WritingOptions.init(rawValue: 0))
Old versions
let myString = yourJsonObject.rawString(NSUTF8StringEncoding, options: NSJSONWritingOptions(rawValue: 0))
To update Tom's answer;
Swift 4 update:
let myString = yourJsonObject.rawString(String.Encoding.utf8, options: JSONSerialization.WritingOptions.init(rawValue: 0))!
Swift 3 update:
let myString = yourJsonObject.rawString(NSUTF8StringEncoding, options: [.jsonSerialization: JSONSerialization.WritingOptions(rawValue: 0)])
Related
I have a String based Key-Value Array inside of a String, and I want to decoded it and assign the value to an existing array in Swift 4.2. For example:
let array: [String:String] = []
let stringToDecode = “[\“Hello\”:\”World\”, \"Key\":\"Value\"]”
// I want ‘array’ to be assigned
// to the value that is inside
// ‘stringToDecode’
I’ve tried the JSON decoder, but it couldn’t decode it. Is there a simple way to do this? Thank you.
Try using a library like SwiftyJson, it makes working with json much easier.
I have a string like this:
let str = "<mylabel>Here is a label</mylabel>"
How can I get a substring with the text "Here is a label" ? Is there any fancy way to do this or do I have to use componentsSeparatedByString?
Many thanks
You can use NSAttributedString(HTML:, documentAttributes:) to extract simple HTML entities:
let str = "<mylabel>Here is a label</mylabel>"
if let html = str.dataUsingEncoding(NSUTF8StringEncoding), let result = NSAttributedString(HTML: html, documentAttributes: nil) {
print(result.string) // "Here is a label"
}
For more complex work, it would be better to use NSXMLParser or a third-party library.
This sorted the issue:
let str = "<mylabel>Here is a label</mylabel>"
let startIndex = str.rangeOfString("<mylabel>")!.last!
let endIndex = str.rangeOfString("</mylabel>")!.first!
print(str.substringWithRange(Range<String.Index>(start: startIndex.advancedBy(1), end: endIndex)))
While you generally would not want to use regular expressions to parse XML/HTML, if you know it will have <mylabel> and </mylabel> you can do something like:
let result = str.stringByReplacingOccurrencesOfString("<mylabel>(.*)</mylabel>", withString: "$1", options: .RegularExpressionSearch, range: nil)
This was working before upgrading to Swift 1.2 and Xcode 6.3.
var mutString : NSMutableAttributedString = NSMutableAttributedString(string: "K2")
mutString.addAttribute(kCTSuperscriptAttributeName, value:-1, range:NSMakeRange(1, 1))
var result : String = mutString.string
The result should contain the string K2 (with "2" as a subscript).
But now I get this error:
Cannot invoke addAttribute with an argument list of type '(CFString!, value:Int, range:NSRange)'
Please point me to the right solution/documentation.
Just add "as! String" after the kCTSuperscriptAttributeName
addAttribute accepts an argument list of type (String, value: AnyObject, range: NSRange). The latter two seem to be fine, but you can't use a CFString! with this method.
You have to use the native Swift String type in Swift 1.2 (which marks a further departure from its Objective-C heritage). Changing kCTSuperscriptAttributeName's type to String should solve the issue.
Attempting to get data on the S&P500 (symbol: ^GSPC) from Yahoo Finance. In playgrounds and scripts, the presence of a caret (^) in the string passed to NSURL errors with "Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, sub code=0x0)". Xcode 6b6 and b7.
Works fine with other ticker symbols (AAPL, MSFT, etc).
Any suggestions for how to get this working?
let symbols:String = "^GSPC"
let financeURL:String = "http://finance.yahoo.com/d/quotes.csv?s=\(symbols)&f=sl1c6p2"
var financeNSURL: NSURL = NSURL(string: financeURL) // ERROR (see above)
let tickerNSData: NSData = NSData(contentsOfURL: financeNSURL)
var output:NSString = NSString(data:tickerNSData, encoding:NSUTF8StringEncoding)
It's crashing because Swift (at least in Xcode6-Beta7) doesn't support returning nil from an object initializer. From the release notes:
Swift does not support object initializers that fail by returning
null. (16480364)
Workaround: If there is a factory method, use it instead. Otherwise,
capture the result in an optional. For example:
let url: NSURL? = NSURL(string: "not a url")
So, to avoid a crash, declare your financeNSURL as NSURL? (as in the example from the docs above), or use NSURL.URLWithString() instead of init(string:).
However, the root of the problem is that you're not encoding your URL parameters correctly.
If you call stringByAddingPercentEncodingWithAllowedCharacters(...) on symbols it works:
let symbols:String = "^GSPC".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let financeURL:String = "http://finance.yahoo.com/d/quotes.csv?s=\(symbols)&f=sl1c6p2"
let financeNSURL: NSURL? = NSURL(string: financeURL)
if let url = financeNSURL {
let tickerNSData: NSData = NSData(contentsOfURL: url)
var output:NSString = NSString(data:tickerNSData, encoding:NSUTF8StringEncoding)
}
Output:
"^GSPC",1999.83,"-2.45","-0.12%"
When creating a NSURLwith init method NSURLWithString: the parameter URLString must be a properly encoded URL string. Your's is not. So, what is this a "properly encoded URL string"?
The corresponding official documentation gives a few more hints where to read:
"URLString: The URL string with which to initialize the NSURL object. This URL string must conform to URL format as described in RFC 2396, and must not be nil. This method parses URLString according to RFCs 1738 and 1808."
(links are mine).
So basically, you need to separately encode each URL component from your source string component using the correct variant of the percent encoding algorithm. Then, compose all encoded string components to the final URL string.
This can be tedious and is certainly error prone. Thus, since iOS 8 there is NSURLComponents (see docs here) which can aid you in this task.
I tried using window.postMessage but this only sends a variable (containing string) to the contentScript. But I want to send a number of variables' values. This seems to be possible by using a JSON object.
Simply use JSON.stringify() to turn the object into a string:
var data = {a: 1, b: 2};
window.postMessage(JSON.stringify(data), "*");
On the other end use JSON.parse() to reverse the process:
var data = JSON.parse(message);
If you use:
self.port.emit('some-event', object)
...and only send objects that can be serialized into JSON properly, the SDK will handle serialization and parsing for you. Here's a quick builder example that illustrates this:
https://builder.addons.mozilla.org/addon/1036506/latest/
I had thought that postMessage would be the same?