2011-07-05 5 views
1

간단한 게임 (iPhone 앱)을 만들고 있는데 사용자가 포인트를 기반으로 순위를 매길 원합니다. 모든 사용자 포인트를 저장 한 다음 앱이 처음 시작될 때 사용자에게 순위를 할당하는 가장 좋은 방법은 무엇입니까? 나는 서버 (웹 사이트)를 가지고 있으므로 필요한 경우 SQL을 사용할 수있다. 어떤 아이디어?사용자의 "순위"를 저장하는 가장 좋은 방법 - iPhone App

답변

1

을 사용하면 mySQL 데이터베이스에서 순위를 읽는 PHP 페이지에 액세스 할 수 있습니다. PHP 출력 xml을 가지고 결과를 파싱합니다. 다음 코드는 PHP 페이지에 요청을 보낸 다음 해당 페이지에서 반환 한 XML을 구문 분석합니다. (DB 항목 등을 업데이트하기 위해 다른 PHP 페이지에 데이터를 게시 할 수도 있습니다.)

//IN THE .h class (of a viewController) 
... : UIViewController { 

    //I use a label to display the data 
    IBOutlet UILabel *label1; 
    //Create global variable 
    NSString *tempString; 
    //Dataset for response from HTTP Request 
    NSMutableData *receivedData; 
    NSXMLParser *xmlParser; 

} 

-(void) initiateAPIConnection; 

@property (nonatomic, retain) NSString *tempString; 

@property (nonatomic, retain) UILabel *label1; 

@end 
//IN THE .h class 


//IN THE .m class 
//... 
@synthesize label1, tempString; 
//... 

-(void)initiateAPIConnection{ 

    NSString *post = [NSString stringWithFormat:@"user=Chris"]; 
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 
    [request setURL:[NSURL URLWithString:@"http://www.yourDomain.com/yourPhpPage.php"]]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [request setTimeoutInterval:10.0]; //fail after 10 seconds with no response 
    [request setHTTPBody:postData]; 

    NSURLConnection *conn=[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease]; 
    if (conn){ 
    NSLog(@"In if conn"); 
    receivedData = [[NSMutableData data] retain]; 
    NSLog(@"End of if conn"); 
    } 
    else{ 
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Conn error" message:@"No Server" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil]; 
    [alert show]; 
    [alert release]; 
    } 

}//initiateAPIConnection 

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ 
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Connection error" message:[error localizedDescription] delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil]; 
    [alert show]; 
    [alert release]; 
} 

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ 
    NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response; 
    NSLog(@"%i",[urlResponse statusCode]); 
    [receivedData setLength:0]; 
} 

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ 
    [receivedData appendData:data]; 
} 

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{ 
    xmlParser = [[NSXMLParser alloc]initWithData:receivedData]; 
    [xmlParser setDelegate:self]; 

    //you may want to enable these features of NSXMLParser. 
    [xmlParser setShouldProcessNamespaces:NO]; 
    [xmlParser setShouldReportNamespacePrefixes:NO]; 
    [xmlParser setShouldResolveExternalEntities:NO]; 
    [xmlParser parse]; 
} 


//XMLdeligate methods 
-(void)parserDidStartDocument:(NSXMLParser *)parser{ 
    NSLog(@"Started Parsing"); 
} 

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{ 
    NSLog(@"Started Element name: %@", elementName); 
} 

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ 
    NSLog(@"Found characters: %@", string); 
    tempString = string; 
} 

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ 
    NSLog(@"Finished Element name: %@", elementName); 

    //my outputted xml would have <ranking>...ValueFromDb...</ranking> in it's response 
    if([elementName isEqualToString:@"ranking"]){ 
    //display result in a label (you could save it to a local variable instead) 
    label1.text = tempString; 
    } 

} 

-(void)parserDidEndDocument:(NSXMLParser *)parser{ 
    NSLog(@"Finished Parsing"); 
} 


//... 


//Don't forget to dealloc 
-(void)dealloc { 
    //... 
    [label1 release]; 
    [tempString release]; 
    [xmlParser release]; 
    [receivedData release]; 
    //... 
    [super dealloc]; 
} 
//IN THE .m class 

자신을 평가하는 사용자의 데이터베이스를 검색하는 데 필요한 논리를 연구해야합니다. 당신은 추가하여 로그인 정보를 전달할 수 있습니다 (예를 들어)? 사용자는 = USERNAME & 패스 = 가리키며 .php 파일의 끝에 PASSWORD ... 즉 ...

[request setURL:[NSURL URLWithString:@"http://www.yourDomain.com/yourPhpPage.php?user=USERNAME&pass=PASSWORD"]]; 

사용자 이름과 암호 값은 샌드 박스에서 읽을 것 등 ... 당신은, 물론

크리스 Allinson

3

Apple Game Center를 살펴 보도록하겠습니다. 그것은 (거의) 미리 만들어진 리더 보드를 포함합니다.

+0

(당신이 stringWithFormat로하는 것처럼) 4.1 이상 기기에서 작동하는 URLWithString를 포맷해야합니다. 나이든 1 세대들에게는 그들을 지원할만한 가치가 있는지를 결정하십시오. 그렇다면 높은 점수를 SQL 서버에 게시하십시오. 점수를 정렬하고 점수를 저장 한 사용자의 ID를 검색하십시오. 그런 다음 해당 순위를 반환합니다. 점수가 여러 개인 경우 랭크를 추가하고 정렬 된 다른 목록에 넣을 수 있으며 순위를 얻을 수 있습니다. – FeifanZ

+0

글쎄, 당신은 iOS 버전의 제한과 관련된 언급을하지 않았다. 이전 버전을 지원할 가치가 있는지 여부를 결정해야합니다. 특히 iOS 5를 사용하면 더욱 그렇습니다. –

-1

그래이 당신이 당신이 사용자가 분류 선택해야이 화면에 대해 서로 다른 기능을 사용할 수 있습니다

당신이 가져 오는 또는 사용자 정보를보고 해당 화면에서 순위 기능을 사용하려면 내 의견으로는 최선의 선택 .. 점수가 점차 감소함에 따라 이러한 종류의 프로그래밍으로 추가 작업을 할 필요가 없습니다.

관련 문제