首页 > 解决方案 > 如何在目标 C 中保存 HTML 字符串中的值?

问题描述

这是我的问题。我正在创建一个登录视图,在该视图中调用返回此 HTML 的 URL:

<html>

<head>

    <meta name = "viewport" content = "width = device-width"></meta>

    <link href="vendor/bootstrap/css/bootstrap.css" rel="stylesheet" />

    <link rel="stylesheet" href="css/wro.css" />

    <link rel="stylesheet" href="css/mobile-form.css" />

    <link rel="stylesheet" href="css/freelancer.css" />

    <link href="css/modal.css" rel="stylesheet" />

    <script src="js/jquery.min.js"></script>

</head>

<body>



    <div class="container" style="margin: 40px auto; text-align: center;">

        <img src="selfblue_logo.png" style="width: 80%; margin-bottom: 40px;"/>

            <form role="form" action="login" method="post" id="mobileForm" class="mobileForm" onsubmit="submit.disabled = true; return true;">    

            <div class="form-group">

                    <label for="username" class="label">Email</label>

                <input type="email" class="form-control" id="username" name="username"/>

            </div>

            <div class="form-group">

                <label for="password" class="label">Password</label>

                <input type="password" class="form-control" id="password" name="password"/>

            </div>

            <input type="hidden" id="csrf_token" name="_csrf" value="29938618-f088-4e1d-a95c-ee0bc5e6a9fd"/>

            <input type="hidden" id="client_id" name="client_id" value="UAPP-195922190062457886232CA834810536 "/>

            <input type="hidden" id="sender" name="sender" value="mobile"/>

            <input type="submit" value="Accedi" id="submit" name="submit"></input>

            </form>

            

        

        <div id="forget">

                <a id="forgetLink" href="/uaa/resetP?client_id=UAPP-195922190062457886232CA834810536">Password dimenticata?</a>

        </div>



    </div>

    

    <script src="js/wro.js" type="text/javascript"></script>

    <script src="vendor/bootstrap/js/bootstrap.min.js"></script>

</body>

</html>

我想要的是保存“csrf_token”的值(d3f1b892-d68c-456e-a2bb-34ba20d3a517),以便稍后将其用于对我的服务器的新调用。我不想使用外部库。

我怎样才能在objective-c中做到这一点?谢谢

标签: htmliosobjective-cxcodeparsing

解决方案


一种有点“蛮力”的方法,假设您确定您正在获取该格式的 html...

用于NSScanner查找通向它的字符串,例如:

name="_csrf" value="

然后找到你正在寻找的“结束”:

"

假设你有你的 html NSString *content,获取它们之间的文本:

NSString *sStart = @"name=\"_csrf\" value=\"";
NSString *sEnd = @"\"";

NSString *scanString = @"";
NSScanner *scanner = [[NSScanner alloc] initWithString:content];

@try {
    [scanner scanUpToString:sStart intoString:nil];
    scanner.scanLocation += [sStart length];
    [scanner scanUpToString:sEnd intoString:&scanString];
}
@catch (NSException *exception) {
    // handle exception...
    NSLog(@"Could not parse csrf value!");
}

NSLog(@"csrf value: %@", scanString);

推荐阅读