ios - How to parse HTML file? - iphone

I'm getting HTML content in below format.
wsse:BinarySecurityToken wsu:Id="uuid:07747f2a-4be4-48fa-9654-5e12235f6040" ValueType="http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0" EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
aHR0cCUzYSUyZiUyZnNjaGVtYXMubWNk</wsse:BinarySecurityToken><
In the below code I'm getting
wsu:Id="uuid:07747f2a-4be4-48fa-9654-5e12235f6040" ValueType="http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0" EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
aHR0cCUzYSUyZiUyZnNjaGVtYXMubWNk
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(_data)
{
NSString* content = [[NSString alloc] initWithData:_data
encoding:NSUTF8StringEncoding];
NSLog(#"Content :%#",content);
NSRange divRange = [content rangeOfString:#"wsse:BinarySecurityToken" options:NSCaseInsensitiveSearch];
if (divRange.location != NSNotFound)
{
NSRange endDivRange;
endDivRange.location = divRange.length + divRange.location;
endDivRange.length = [content length] - endDivRange.location;
endDivRange = [content rangeOfString:#"=<" options:NSCaseInsensitiveSearch range:endDivRange];
if (endDivRange.location != NSNotFound)
{
divRange.location += divRange.length;
divRange.length = endDivRange.location - divRange.location;
NSLog(#"BinarySecurityToken : %#",[content substringWithRange:divRange]);
}
}
[webView loadHTMLString:content baseURL:_url];
}
}
I want the Output as aHR0cCUzYSUyZiUyZnNjaGVtYXMubWNk.
Any ideas? Thanks in advance.

As you discussing you have NSString *token = #"<wsse:BinarySecurityToken>aHR0cCUzYSUyZiUyZnNjaGVtYWd0Sjk0JTNk</wsse:BinarySecurityToken>";
and what the token between tags then you can replace the unwanted character like .
NSString *str = [token stringByReplacingOccurrencesOfString:#"<wsse:BinarySecurityToken>"
withString:#""];;
and then
NSString *correctToken = [str stringByReplacingOccurrencesOfString:#"</wsse:BinarySecurityToken>"
withString:#""];;

Related

Proper Encoding for chines character from NSData

Please help me i'm using below code to get file name.
Here i'm getting NSString from NSData where multipartData is NSMutableArray which contain NSData.
NSString* postInfo = [[NSString alloc] initWithBytes:[[multipartData objectAtIndex:1] bytes] length:[[multipartData objectAtIndex:1] length] encoding:NSUTF8StringEncoding];
I'm getting string like:
Printing description of postInfo:
Content-Disposition: form-data; name="file"; filename="??:??.PNG"
But It should be like:
Printing description of postInfo:
Content-Disposition: form-data; name="file"; filename="华语/華語.PNG"
Thanks in advance.
Obviously the server doesn't encode the response using UTF-8, but probably another Chinese-only encoding. You need to use the Content-Type header to detect which encoding it is, and then find the appropriate NSStringEncoding using the following code;
// set charset to the MIME charset you get from the server
CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)(charset)));
Here is a detailed answer:
// getting the Content-Type header (e.g. "application/json; charset=utf-8")
NSString* header = [[response allHeaderFields] objectForKey:#"Content-Type"];
// getting the MIME type
NSString* charset = nil;
NSArray* contentTypeParts = [header componentsSeparatedByString:#";"];
NSInteger i = 0;
for (NSString* part in contentTypeParts) {
// ignoring first loop (e.g. "application/json")
if (i > 0) {
NSArray* partComponents = [part componentsSeparatedByString:#"="];
if ([partComponents count] == 2 && [#"charset" isEqualToString:[[partComponents objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]]) {
charset = [[partComponents objectAtIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
break;
}
}
i++;
}
// converting the MIME type to NSStringEncoding
NSStringEncoding stringEncoding = NSUTF8StringEncoding; // default to UTF8
if (charset) {
stringEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)(charset)));
}
// finally you can convert your string properly!
NSString* postInfo = [[NSString alloc] initWithBytes:[[multipartData objectAtIndex:1] bytes] length:[[multipartData objectAtIndex:1] length] encoding:stringEncoding];

How to remove starting 0's in uitextfield text in iphone sdk

Code Snippet:
NSString *tempStr = self.consumerNumber.text;
if ([tempStr hasPrefix:#"0"] && [tempStr length] > 1) {
tempStr = [tempStr substringFromIndex:1];
[self.consumerNumbers addObject:tempStr];>
}
I tried those things and removing only one zero. how to remove more then one zero
Output :001600240321
Expected result :1600240321
Any help really appreciated
Thanks in advance !!!!!
Try to use this one
NSString *stringWithZeroes = #"001600240321";
NSString *cleanedString = [stringWithZeroes stringByReplacingOccurrencesOfString:#"^0+" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, stringWithZeroes.length)];
NSLog(#"Clean String %#",cleanedString);
Clean String 1600240321
convert string to int value and re-assign that value to string,
NSString *cleanString = [NSString stringWithFormat:#"%d", [string intValue]];
o/p:-1600240321
You can add a recursive function that is called until the string begin by something else than a 0 :
-(NSString*)removeZerosFromString:(NSString *)anyString
{
if ([anyString hasPrefix:#"0"] && [anyString length] > 1)
{
return [self removeZerosFromString:[anyString substringFromIndex:1]];
}
else
return anyString;
}
so you just call in your case :
NSString *tempStr = [self removeZerosFromString:#"000903123981000"];
NSString *str = #"001600240321";
NSString *newStr = [#([str integerValue]) stringValue];
If the NSString contains numbers only.
Other wise use this:
-(NSString *)stringByRemovingStartingZeros:(NSString *)string
{
NSString *newString = string;
NSInteger count = 0;
for(int i=0; i<[string length]; i++)
{
if([[NSString stringWithFormat:#"%c",[string characterAtIndex:i]] isEqualToString:#"0"])
{
newString = [newString stringByReplacingCharactersInRange:NSMakeRange(i-count, 1) withString:#""];
count++;
}
else
{
break;
}
}
return newString;
}
Simply call this method:-
NSString *stringWithZeroes = #"0000000016909tthghfghf";
NSLog(#"%#", [self stringByRemovingStartingZeros:stringWithZeroes]);
OutPut: 16909tthghfghf
Try the `stringByReplacingOccurrencesOfString´ methode like this:
NSString *new = [old stringByReplacingOccurrencesOfString: #"0" withString:#""];
SORRY: This doesn't help you due to more "0" in the middle part of your string!

ios - How to parse HTML content in ios?

How do I parse HTML file?
I'm getting an HTML file in the below code,I just want to get data in between BinarySecurityToken XML node.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(_data)
{
//Here am getting the below HTML content
NSString* content = [[NSString alloc] initWithData:_data
encoding:NSUTF8StringEncoding];
}
}
<input type="hidden" name="wa" value="wsignin1.0" />
<input type="hidden" name="wresult"
value="<t:RequestSecurityTokenResponse xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
<t:Lifetime>
<wsu:Created >2013-04-29T11:50:29.895Z</wsu:Created>
<wsu:Expires>2013-04-29T12:00:29.895Z</wsu:Expires>
</t:Lifetime>
<wsp:AppliesTo>
<EndpointReference>
<Address>urn:orin.converse</Address>
</EndpointReference></wsp:AppliesTo>
<t:RequestedSecurityToken>
<wsse:BinarySecurityToken>
aHR0cCUzYSUyZiUyZnNjaGVtYWd0Sjk0JTNk
</wsse:BinarySecurityToken>
Any ideas? Thanks in advance.
You can get using this code
NSRange divRange = [content rangeOfString:#"<wsse:BinarySecurityToken>" options:NSCaseInsensitiveSearch];
if (divRange.location != NSNotFound)
{
NSRange endDivRange;
endDivRange.location = divRange.length + divRange.location;
endDivRange.length = [content length] - endDivRange.location;
endDivRange = [content rangeOfString:#"</wsse:BinarySecurityToken>" options:NSCaseInsensitiveSearch range:endDivRange];
if (endDivRange.location != NSNotFound)
{
divRange.location += divRange.length;
divRange.length = endDivRange.location - divRange.location;
NSLog(#"BinarySecurityToken : %#",[content substringWithRange:divRange]);
}
}
Output :
aHR0cCUzYSUyZiUyZnNjaGVtYWd0Sjk0JTNk
You need and XML parser for that.
There's a tutorial here
For this particular case you can get the ranges of <wsse:BinarySecurityToken> and </wsse:BinarySecurityToken>, construct new range that will provide you location of the token, and get substring in that range.
Sample code:
NSRange openingTagRange = [htmlString rangeOfString:#"<wsse:BinarySecurityToken>"];
NSRange closingTagRange = [htmlString rangeOfString:#"</wsse:BinarySecurityToken>"];
NSRange tokenRange = NSMakeRange(openingTagRange.location + openingTagRange.length, closingTagRange.location - (openingTagRange.location + openingTagRange.length));
NSString *token = [htmlString substringWithRange:tokenRange];
Since your input comes from outside, you should probably check if the ranges' locations are not equal to NSNotFound.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"];
NSData * data = [NSData dataWithContentsOfFile:filePath];
TFHpple * tutorialsParser = [[TFHpple alloc] initWithHTMLData:data];
NSString *query = #"//div[#id='BinarySecurityToken']";
NSArray *nodes = [tutorialsParser searchWithXPathQuery:query];
for (TFHppleElement * element in nodes) {
NSLog(#"%#", element);
NSLog(#"%#", [element tagName]);
NSLog(#"%#", [element attributes]);
NSLog(#"%#", [element children]);
for (TFHppleElement *childElement in [element children]) {
NSLog(#"%#", childElement);
}
}
hope this will help you For more try this blog and Git Project Resource may help you and
Good blog by RAYWENDERLICH
or another option if you have all the HTML data in NSString you can get data between specific NSString with this function.
-(NSString*)stringBetweenString:(NSString*)start andString:(NSString)end {
NSRange startRange = [self rangeOfString:start];
if (startRange.location != NSNotFound) {
NSRange targetRange;
targetRange.location = startRange.location + startRange.length;
targetRange.length = [self length] - targetRange.location;
NSRange endRange = [self rangeOfString:end options:0 range:targetRange];
if (endRange.location != NSNotFound) {
targetRange.length = endRange.location - targetRange.location;
return [self substringWithRange:targetRange];
}
}
return nil;
}

How to search for NSMutablearray content in substring of a NSString?

I created an NSMutableArray and am searching/matching the content of array with NSString's substring but how to do it?
NSMutableArray *tmparray = {#"PPG" , #"AG" , #"HD" };
NSString *tmpstring = #"MAAPPG";
if ([tmparray containsObject:tmpstring] ) {
NSLog(#"String found");
}
But it's not happening because tmparray contain "PPG" not "MAAPPG" how to search for substring matching ?
You can use an NSPredicate to do this, but it may be slow. Here's a simpler approach along the lines of what your trying:
NSMutableArray *tmparray = {#"PPG" , #"AG" , #"HD" };
NSString *tmpstring = #"MAAPPG";
NSRange *tmprange;
for(NSString *string in tmparray) {
tmprange = [tmpstring rangeOfString:string];
if (tmprange.location != NSNotFound) {
NSLog(#"String found");
break;
}
}
how about this
for(NSString *arrString in tmparray){
if([tmpstring rangeOfString:arrString].location != NSNotFound){
NSLog(#"String found");
}
}
NSArray *tmparray = [NSArray arrayWithObjects:#"PPG" , #"AG" , #"HD",nil];
NSString *tmpstring = #"MAAPPG";
NSRange textRange;
for(NSString *string in tmparray)
{
textRange =[tmpstring rangeOfString:string];
if(textRange.location != NSNotFound)
{
NSLog(#"String found ");
}
}
check this by using other substrings also...

Retrieving a filename for an ALAsset

How can the filename be extracted from an ALAsset?
Is there a way to get this via the url or some other way?
From iOS 5.0 you can get the file from ALAssetRepresentation Class.
ALAssetRepresentation *rep = [anAssetItem defaultRepresentation];
NSString *fileName = [rep filename];
Update: As yeonsh notes below, from iOS 5.0 there is a better way. This answer is relevant for iOS < 5.0.
You can extract an URL from the ALAsset, but all the filenames are the same, on the form
assets-library://asset/asset.JPG?id=1000000001&ext=JPG
If you for some reason need different file names, try making an internal-external paradigm:
#import <Foundation/Foundation.h>
#interface NSURL (NSURL_Asset)
- (NSURL*) toExternalForm;
- (NSURL*) fromExternalForm;
- (NSString*) toExternalFilename;
#end
#import "NSURL+Asset.h"
#import "URLParser.h" // from http://iphone.demay-fr.net/2010/04/parsing-url-parameters-in-a-nsstring/
static NSString *const EXTERNAL_TOKEN = #"/assetExternalForm/";
#implementation NSURL (NSURL_Asset)
// assets-library://asset/asset.JPG/assetExternalForm/1000000001.JPG -> assets-library://asset/asset.JPG?id=1000000001&ext=JPG
- (NSURL*) fromExternalForm {
if([self.scheme isEqualToString:#"assets-library"]) {
NSRange slash = [self.absoluteString rangeOfString:EXTERNAL_TOKEN options:NSBackwardsSearch];
if(slash.location != NSNotFound) {
NSRange dot = [self.absoluteString rangeOfString:#"." options:NSBackwardsSearch];
if(dot.location != NSNotFound) {
NSString* extention = [self.absoluteString substringFromIndex:(dot.location + dot.length)];
NSString* identifier = [self.absoluteString substringWithRange:NSMakeRange(slash.location + slash.length, dot.location - (slash.location + slash.length))];
return [NSURL URLWithString:[NSString stringWithFormat:#"%#?id=%#&ext=%#", [self.absoluteString substringToIndex:slash.location], identifier, extention]];
}
}
}
return self;
}
// assets-library://asset/asset.JPG?id=1000000001&ext=JPG -> assets-library://asset/asset.JPG/assetExternalForm/1000000001.JPG
- (NSURL*) toExternalForm {
if([self.scheme isEqualToString:#"assets-library"]) {
NSRange range = [self.absoluteString rangeOfString:#"?"];
if(range.location != NSNotFound) {
URLParser *parser = [[[URLParser alloc] initWithURLString:self.absoluteString] autorelease];
NSString* extention = [parser valueForVariable:#"ext"];
NSString* identifier = [parser valueForVariable:#"id"];
if(extention != NULL && identifier != NULL) {
return [NSURL URLWithString:[NSString stringWithFormat:#"%#%#%#.%#", [self.absoluteString substringToIndex:range.location], EXTERNAL_TOKEN, identifier, extention]];
}
}
}
return self;
}
// assets-library://asset/asset.JPG?id=1000000001&ext=JPG -> 1000000001.JPG
- (NSString*) toExternalFilename {
if([self.scheme isEqualToString:#"assets-library"]) {
NSRange range = [self.absoluteString rangeOfString:#"?"];
if(range.location != NSNotFound) {
URLParser *parser = [[[URLParser alloc] initWithURLString:self.absoluteString] autorelease];
NSString* extention = [parser valueForVariable:#"ext"];
NSString* identifier = [parser valueForVariable:#"id"];
if(extention != NULL && identifier != NULL) {
return [NSString stringWithFormat:#"%#.%#", identifier, extention];
}
}
}
return NULL;
}
#end
Note that you do not need a filename to read the content of an ALAsset. Use the ALAsset.defaultRepresentation.getBytes method for that.