如何在ios应用程序中使用post data和json

时间:2012-07-25 06:38:38

标签: iphone ios xcode json

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"ht...y.php"]];
[request setHTTPMethod:@"POST"];
NSString *postString = [NSString stringWithFormat: @"User=A&Pass=1"];
[request setValue:[NSString stringWithFormat:@"%d", [postString length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSHTTPURLResponse *urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];

dispatch_async(kBgQueue, ^{
NSData* data2 = [NSData dataWithContentsOfURL: notyURL];
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:data2 waitUntilDone:YES];});

如何让dispatch_async使用数据而不是data2?

1 个答案:

答案 0 :(得分:1)

我建议使用NSURLConnection类方法sendSynchronousRequest,而不是使用dispatch_asyncsendAsynchronousRequest,如下所示:

[NSURLConnection sendAsynchronousRequest:request 
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];

}];