如何将Content-Disposition表单数据保存到NSString

时间:2017-03-05 15:46:59

标签: ios objective-c iphone nsstring nsdata

我从NSData对象中创建了一个NSString:

   NSData* data = request.HTTPBody;
    NSString* s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

现在我有了NSString,它给了我以下NSLog:

    WebKitFormBoundaryA7rpc3udSxxsvBFm

Content-Disposition: form-data; name="username"

Testusernamevalue

------WebKitFormBoundaryA7rpc3udSxxsvBFm

Content-Disposition: form-data; name="password"

Testpasswordvalue

------WebKitFormBoundaryA7rpc3udSxxsvBFm--

如何将“username”和“password”这两个值保存到用户名和密码的单个NSString中?

感谢您的帮助。 最好的祝福 EDDI

1 个答案:

答案 0 :(得分:0)

我认为我理解这个问题意味着我们希望字符串值位于" Content-Disposition"之后的行上。线。为此,我们需要遍历各个方面,保持关于查找分界线及其类型(用户名或密码)的状态

NSArray *components = [theLongContentDispositionString componentsSeparatedByString:@"\n"];
NSMutableDictionary *values = [NSMutableDictionary dictionary];

NSString *key = nil;
for (NSString *line in components) {
    if (key && line.length) {
        values[key] = line;
        key = nil;
    } else if ([line hasPrefix:@"Content-Disposition"]) {
        // does the line contain "username"?  Assume password if not
        NSRange r = [line rangeOfString:@"username"];
        key = (r.location == NSNotFound)? @"password" : @"username";
    }
}

值词典应该看起来像:

{
    password = "non-empty line after Content-Disposition line with password";
    username = "non-empty line after Content-Disposition line with username";
}