我有一个运行 sql server 数据库的服务器,我可以将数据从它发送到我的 iPhone。这是我使用的代码:
服务器上的 PHP
<?php
$headers = getallheaders();
$length = $headers['Content-Length'];
$input = fopen("php://input", "rb");
$json = json_decode(fread($input, $length));
fclose($input);
$search = $json->{'search'};
$value = $json->{'value'};
$serverName = "SOMEONE-PC\SQLEXPRESS";
$connectionInfo = array( "Database"=>"test");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$sql = "SELECT firstname, lastname
FROM testtable
WHERE $search='$value'";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
while( $row = sqlsrv_fetch_array( $stmt ) ) {
$arr = array('firstname' => $row['firstname'], 'lastname' => $row['lastname']);
echo json_encode($arr);
}
?>
我的 Objective-C 代码
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSString *urlString = @"http://someipaddress";
NSString *post = @"{\"search\":\"lastname\",\"value\":\"mylastname\"}";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"%i", ++_count);
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse*)cachedResponse {
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"%@", [[NSString alloc] initWithData:_responseData encoding:NSStringEncodingConversionAllowLossy]);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
这给了我输出:
2013-11-12 22:58:03.743 httppostrequests[25708:70b] 1
2013-11-12 22:58:03.745 httppostrequests[25708:70b] {"firstname":"Thomas ","lastname":"mylastname"}{"firstname":"person ","lastname":"mylastname"}
我想知道是否可以更改服务器代码,以便多次调用 didRecieveData 以便数据以位发送而不是作为一个大文本发送。我只是好奇这是如何工作的,因为当我向“ http://www.google.com ”发出一个简单的请求时,didRecieveData 会被调用四次。