我是iOS新手我需要使用post方法响应在textview或picker视图中显示特定对象的键。
编码:
NSString *parameter = [NSString stringWithFormat:@"username=%@",user];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(@"%@", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
NSString *content = [NSString stringWithUTF8String:[parameterData bytes]];
}
[request setHTTPMethod:method];
[request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if( connection )
{
mutableData = [NSMutableData new];
}
}
委托方法:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseStringWithEncoded = [[NSString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
// NSLog(@"Response from Server : %@", responseStringWithEncoded);
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error]; //Now we got top level dictionary
// (2)
arrdata =[json objectForKey:@"Branches"];
//(2)
NSLog(@"%@",[arrdata valueForKey:@"id"]);
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
serverResponse.attributedText = attrStr;
//serverResponse.text = arrdata;
}
我在NSLOG成功展示如下:
但在textview
中,它没有更新。我该如何解决这个问题?
答案 0 :(得分:0)
serverResponse.text = [arrdata valueForKey:@"id"];
答案 1 :(得分:0)
所有UI更改必须在主线程中执行。
因此可能是这个问题。
所以,在connectionDidFinishLoading
包裹textview
的末尾有GCD主队列,如下所示:
dispatch_async(dispatch_get_main_queue(),^ {
//Update text view
serverResponse.attributedText = attrStr;
});
答案 2 :(得分:0)
试用以下代码:
dispatch_async(dispatch_get_main_queue(),^ {
//Update your UI Component here
serverResponse.attributedText = attrStr;
//or uncomment below line and comment upper line
//serverResponse.text = [arrdata valueForKey:@"id"];
});