I wants to generate XML string something like this in swift -
<userTracking>
<userDetail id='1178085'>xxxx</userDetail>
<trackInfo type="xxxxx" type_id="xxxxxxx" attending="x" event_date="2016-07-01"/>
</userTracking>
for this i had objective-C code -
NSString *post = #"";
post = [NSString stringWithFormat:
#"<userTracking>"
#"<userDetail id=\'%#\'>xxxxx</userDetail>"
#"<trackInfo type=\"%#\" type_id=\"%#\" attending=\"%#\" event_date=\"%#\"/>"
#"</userTracking>"
, UserID,type, typeID, attending,event_date];
which is working great. Now i wants to generate same thing in swift & done following code but getting wrong XML formatted string -
swift Code -
var post = "";
post = "<userTracking>" +
"<userDetail id='\(UserID)\'>xxxxx</userDetail>" +
"<trackInfo type=\"\(type)\" type_id=\"\(typeID)\" attending=\"\(attending)\" event_date=\"\(event_date)\"/>" +
"</userTracking>";
Result in Swift -
<userTracking>
<userDetail id=\'xxxxx\'>xxxxx</userDetail>
<trackInfo type=\"xxxx\" type_id=\"xxx\" attending=\"4\" event_date=\"2016-07-01\"/>
</userTracking>
any help will be appreciated.
You can also use String(format:) in Swift.
Don't forget to escape all double quotes, and add newlines ("\n") and tabs ("\t") if needed.
Example:
let post = String(format: "<userTracking>\n\t<userDetail id=\'%#\'>xxxxx</userDetail>\n\t<trackInfo type=\"%#\" type_id=\"%#\" attending=\"%#\" event_date=\"%#\"/>\n</userTracking>", UserID, type, typeID, attending, event_date)
Gives:
<userTracking>
<userDetail id='...'>xxxxx</userDetail>
<trackInfo type="..." type_id="..." attending="..." event_date="..."/>
</userTracking>
Related
I want to append a unichar to NSMutableString. I have
var outputString: NSMutableString = "Some string"
let letterA: unichar = 0x1820
I saw the question Appending unichar to NSMutableString. The accepted answer (in Objective C) says:
[s appendFormat:#"%C", c];
but I can't figure out the Swift syntax. The documentation doesn't help much, either.
I even tried
outputString += letterA
but that also didn't work.
Note: I'm not trying to append a Swift String or append a Swift Character.
Use the same method appendFormat in swift like this
Rewriting your code to elaborate
var outputString: NSMutableString = "Some string"
let letterA: unichar = 0x1820
outputString.appendFormat("%C", letterA)
outputString.appendFormat("%C", letterA) appends the character in Swift 1.2 running in Xcode 6.4. It appears to be the same method you've referenced in the Objective-C sample.
NSMutableString
The NSMutableString reference does not need to be a var
let outputString:NSMutableString = "Some string"
outputString.appendFormat("%C", 0x0041) // Letter A
Native Swift String
Solution skipping NSFoundation and unichar classes:
var outputString = "Some string"
outputString += "\u{41}" // Letter A is actually 0x0041
I just worried to parse the JSON data as below format. Here I need to parse userId as string or integer.
(
{
Response = success;
UserId = 214;
}
)
In my previous workout data is fetching like this ( 214 ).
If its coming like (214), why don't you try doing substring on it. Performing substring will remove the starting and ending braces. Try something like this.
NSString *badStr = #"(214)";
NSString *goodStr = [badStr substringFromIndex:1];
NSString *finalStr = [goodStr substringToIndex:[goodStr length]-1];
This will help you get the exact 214 value without the braces.
Hope this helps.
I need to have a string like this,
Content-Disposition = name="uploaded file" in my HTTP request header.
I tried using escape sequences \" like this (as mentioned here)
NSString *valueString = #"name=\"uploadedfile\" ";
it returns me an output like this : "Content-Disposition" = "name=\"uploadedfile\"";
how can i do this? Please help. Thanks.
I have following strings. But I need to separate them by this "jsonp1343930692" and assign them NSString again. How could I that? I could able to separate them to NSArray but I don't know how to separate to NSString.
jsonp1343930692("snapshot":[{"timestamp":1349143800,"data":[{"label_id":10,"lat":29.7161,"lng":-95.3906,"attr":{"ozone_level":37,"exp":"IN","gridpoint":"29.72:-95.39"}},{"label_id":10,"lat":30.168456,"lng":-95.50448}]}]})
jsonp1343930692("snapshot":[{"timestamp":1349144700,"data":[{"label_id":10,"lat":29.7161,"lng":-95.3906,"attr":{"ozone_level":37,"exp":"IN","gridpoint":"29.72:-95.39"}},{"label_id":10,"lat":30.168456,"lng":-95.50448,"attr":{"ozone_level":57,"exp":"IN","gridpoint":"30.17:-95.5"}},{"label_id":10,"lat":29.036944,"lng":-95.438333}]}]})
The jsonp1343930692 prefix in your string is odd: I don't know where you string come from, but it really seems to be some JSON string with this strange prefix that has no reason to be there. The best shot here is probably to check if it is normal to have this prefix, for example if you get this string from a WebService it is probably the WebService fault to return this odd prefix.
Anyway, if you want to remove the jsonp1343930692 prefix of your string, you have multiple options:
Check that the prefix is existant, and if so, remove the right number of characters from the original string:
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
if ([str hasPrefix:kStringToRemove])
{
// rebuilt a string by only using the substring after the prefix
str = [str substringFromIndex:kStringToRemove.length];
}
Split your string in multiple parts, using the jsonp1343930692 string as a separator
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
NSArray* parts = [str componentsSeparatedByString:kStringToRemove];
str = [parts componentsJoinedByString:#""];
Replace every occurrences of jsonp1343930692 by the empty string.
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
str = [str stringByReplacingOccurrencesOfString:kStringToRemove withString:#""];
So in short you have many possibilities depending on what exactly you want to do :)
Of course, once you have removed your strange jsonp1343930692 prefix, you can deserialize your JSON string to obtain a JSON object (either using some third-party lib like SBJSON or using NSJSONSerializer on iOS5 and later, etc)
Have a look at the NSJSONSerialization class to turn this into a Cocoa collection that you can deal with.
In Objective-C for iOS, how would I remove the last character of a string using a button action?
In your controller class, create an action method you will hook the button up to in Interface Builder. Inside that method you can trim your string like this:
if ([string length] > 0) {
string = [string substringToIndex:[string length] - 1];
} else {
//no characters to delete... attempting to do so will result in a crash
}
If you want a fancy way of doing this in just one line of code you could write it as:
string = [string substringToIndex:string.length-(string.length>0)];
*Explanation of fancy one-line code snippet:
If there is a character to delete (i.e. the length of the string is greater than 0)
(string.length>0) returns 1 thus making the code return:
string = [string substringToIndex:string.length-1];
If there is NOT a character to delete (i.e. the length of the string is NOT greater than 0)
(string.length>0) returns 0 thus making the code return:
string = [string substringToIndex:string.length-0];
Which prevents crashes.
If it's an NSMutableString (which I would recommend since you're changing it dynamically), you can use:
[myString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];
The solutions given here actually do not take into account multi-byte Unicode characters ("composed characters"), and could result in invalid Unicode strings.
In fact, the iOS header file which contains the declaration of substringToIndex contains the following comment:
Hint: Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up composed characters
See how to use rangeOfComposedCharacterSequenceAtIndex: to delete the last character correctly.
The documentation is your friend, NSString supports a call substringWithRange that can shorten the string that you have an return the shortened String. You cannot modify an instance of NSString it is immutable. If you have an NSMutableString is has a method called deleteCharactersInRange that can modify the string in place
...
NSRange r;
r.location = 0;
r.size = [mutable length]-1;
NSString* shorted = [stringValue substringWithRange:r];
...