【发布时间】:2016-12-19 05:10:57
【问题描述】:
我有两个名为密码字段的文本字段,我将该文本保存在一个名为“Firststring”的字符串中。
我的疑问是如何将字符串值分配给我的 jsonDict 并进行 Web 服务发布调用?
【问题讨论】:
标签: ios objective-c
我有两个名为密码字段的文本字段,我将该文本保存在一个名为“Firststring”的字符串中。
我的疑问是如何将字符串值分配给我的 jsonDict 并进行 Web 服务发布调用?
【问题讨论】:
标签: ios objective-c
你的方法是对的,你可以使用 Keys 直接将你的字符串添加到 Dict
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
[jsonDict setObject:@"staticname" forKey:@"albert"];
[jsonDict setObject:Firststring forKey:@"password"];
update-1
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"YOUR URL HERE"]];
[req setHTTPMethod:@"POST"];
NSError *error = nil;
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
[jsonDict setObject:@"staticname" forKey:@"albert"];
[jsonDict setObject:Firststring forKey:@"password"];
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDict
options:kNilOptions error:&error];
NSString *postLength = [NSString stringWithFormat:@"%d",[data length]];
[req addValue:postLength forHTTPHeaderField:@"Content-Length"];
[req setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:req
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Do something
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", json);
}];
[task resume];
选择 2
// 1
NSURL *url = [NSURL URLWithString:@"YOUR_WEBSERVICE_URL"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
// 2
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";
// 3
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
[jsonDict setObject:@"staticname" forKey:@"albert"];
[jsonDict setObject:Firststring forKey:@"password"];
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDict
options:kNilOptions error:&error];
if (!error) {
// 4
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
// Handle response here
// handle response
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", json);
}];
// 5
[uploadTask resume];
注意 - 如果你想在 iOS 9 中访问服务器,你需要在你的 .PList 中添加 NSAllowsArbitraryLoads 例如参见 This
【讨论】:
像这样:
NSDictionary *jsonDict = @{@"staticname":@"albert",
@"password":password};
【讨论】:
使用以下方法发布数据。
-(IBAction)login:(id)sender{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:self.txtUsername.text forKey:@"txt_user_email"];
[dict setObject:self.txtPassword.text forKey:@"txt_user_pass"];
[self postMethodWithDict:dict andURL:@"http:your API url here" ];
}
-(void) postMethodWithDict:(NSDictionary *)dict andURL:(NSString *)url{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setTimeoutInterval:30];
NSString *boundary = [NSString stringWithFormat:@"14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@\\r\\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"sending data %@", dict);
// additional method to call in between
NSData *data = [self createFormData:dict withBoundary:boundary];
[body appendData:[[NSString stringWithFormat:@"\\r\\n--%@\\r\\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:data];
[request setHTTPBody:body];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
if(conn) {
// connection success
NSLog(@"connection success");
}
else {
// deal with error
NSLog(@"error occured");
}
}
// linked method
- (NSData*)createFormData:(NSDictionary*)myDictionary withBoundary:(NSString*)myBounds {
NSMutableData *myReturn = [[NSMutableData alloc] init];
NSArray *formKeys = [myDictionary allKeys];
for (int i = 0; i < [formKeys count]; i++) {
[myReturn appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",myBounds] dataUsingEncoding:NSASCIIStringEncoding]];
[myReturn appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n%@",[formKeys objectAtIndex:i], [myDictionary valueForKey:[formKeys objectAtIndex:i]]] dataUsingEncoding:NSASCIIStringEncoding]];
}
return myReturn;
}
使用 NSURLConnection 委托方法来获取你的 api 的所有响应
【讨论】: