'iphone'에 해당되는 글 2건
- 2011/04/25 iphone에서 http 사용하기 (get/post) - 소스코드는 퍼왔습니다.
- 2009/08/05 [iphone,sqlite3] no such table 오류가 날 경우 / 연동방법
아래의 코드와 같이 실제 값이 앞에 가고 뒤에 이름이 들어간다.
[뷰에 클릭후 http를 생성 및 초기 코드]
// url 문자열을 이용하여 HTTP로 웹사이트에 접속
- (void)requestUrl {
// 접속할 주소 설정
NSString *url = @"http://사용자의 웹 페이지 주소";
// HTTP Request 인스턴스 생성
HTTPRequest *httpRequest = [[HTTPRequest alloc] init];
// POST로 전송할 데이터 설정
NSDictionary *bodyObject = [NSDictionary dictionaryWithObjectsAndKeys:
@"38.0", @"latitude",
@"127.0", @"longitude",
nil];
//NSString *bodyObject = @"type=getUser&seq=1&latitude=38.0&longitude=127.0&time=13600&unit='k'&distance=9999";
// 통신 완료 후 호출할 델리게이트 셀렉터 설정
[httpRequest setDelegate:self selector:@selector(didReceiveFinished:)];
// 페이지 호출
[httpRequest requestUrl:url bodyObject:bodyObject];
//
[spinner startAnimating];
}
아래 코드들은 클래스 생성후에 내용을 추가 해야 합니다.
[HTTPRequest.h]
#import <Foundation/Foundation.h>
@interface HTTPRequest : NSObject
{
NSMutableData *receivedData;
NSURLResponse *response;
NSString *result;
id target;
SEL selector;
}
- (BOOL)requestUrl:(NSString *)url bodyObject:(NSDictionary *)bodyObject;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- (void)setDelegate:(id)aTarget selector:(SEL)aSelector;
@property (nonatomic, retain) NSMutableData *receivedData;
@property (nonatomic, retain) NSURLResponse *response;
@property (nonatomic, assign) NSString *result;
@property (nonatomic, assign) id target;
@property (nonatomic, assign) SEL selector;
@end
[HTTPRequest.m]
#import "HTTPRequest.h"
@implementation HTTPRequest
@synthesize receivedData;
@synthesize response;
@synthesize result;
@synthesize target;
@synthesize selector;
- (BOOL)requestUrl:(NSString *)url bodyObject:(NSDictionary *)bodyObject
{
// URL Request 객체 생성
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:5.0f];
// 통신방식 정의 (POST, GET)
[request setHTTPMethod:@"POST"];
// bodyObject의 객체가 존재할 경우 QueryString형태로 변환
if(bodyObject)
{
// 임시 변수 선언
NSMutableArray *parts = [NSMutableArray array];
NSString *part;
id key;
id value;
// 값을 하나하나 변환
for(key in bodyObject)
{
value = [bodyObject objectForKey:key];
part = [NSString stringWithFormat:@"%@=%@", [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[parts addObject:part];
}
// 값들을 &로 연결하여 Body에 사용
[request setHTTPBody:[[parts componentsJoinedByString:@"&"] dataUsingEncoding:NSUTF8StringEncoding]];
}
// Request를 사용하여 실제 연결을 시도하는 NSURLConnection 인스턴스 생성
NSURLConnection *connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
// 정상적으로 연결이 되었다면
if(connection)
{
// 데이터를 전송받을 멤버 변수 초기화
receivedData = [[NSMutableData alloc] init];
return YES;
}
return NO;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse
{
// 데이터를 전송받기 전에 호출되는 메서드, 우선 Response의 헤더만을 먼저 받아 온다.
//[receivedData setLength:0];
self.response = aResponse;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 데이터를 전송받는 도중에 호출되는 메서드, 여러번에 나누어 호출될 수 있으므로 appendData를 사용한다.
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// 에러가 발생되었을 경우 호출되는 메서드
NSLog(@"Error: %@", [error localizedDescription]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 데이터 전송이 끝났을 때 호출되는 메서드, 전송받은 데이터를 NSString형태로 변환한다.
result = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
// 델리게이트가 설정되어있다면 실행한다.
if(target)
{
[target performSelector:selector withObject:result];
}
}
- (void)setDelegate:(id)aTarget selector:(SEL)aSelector
{
// 데이터 수신이 완료된 이후에 호출될 메서드의 정보를 담고 있는 셀렉터 설정
self.target = aTarget;
self.selector = aSelector;
}
- (void)dealloc
{
[receivedData release];
[response release];
[result release];
[super dealloc];
}
@end
[iphone,sqlite3] no such table 오류가 날 경우 / 연동방법

-(void) readAnimalsFromDatabase {
// Setup the database object
sqlite3 *database;
// Init the animals Array
// animals = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
if(sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
NSString* sqlStatement = [NSString stringWithFormat:@"select * from s1"];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
int idx = sqlite3_column_int( compiledStatement, 0 );
int level = sqlite3_column_int( compiledStatement, 1 );
int c1 = sqlite3_column_int( compiledStatement, 2 );
int c2 = sqlite3_column_int( compiledStatement, 3 );
int c3 = sqlite3_column_int( compiledStatement, 4 );
// Create a new animal object with the data from the database
// Animal *animal = [[Animal alloc] initWithName:aName description:aDescription url:aImageUrl];
// Add the animal object to the animals Array
// [animals addObject:animal];
// [animal release];
}
}
else
{
NSString* msg = [[NSString alloc] initWithFormat:@"%s", sqlite3_errmsg( database )];
NSLog( @"Failed to open database with message '%s'.", sqlite3_errmsg( database ) );
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
** 연동 방법에 대해서는 따로 적지를 않았습니다.
-(void) checkAndCreateDatabase{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:[self dataFilePath]];
// If the database already exists then return without doing anything
if(success) return;
// If not then proceed to copy the database from the application to the users filesystem
// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kFilename];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:[self dataFilePath] error:nil];
[fileManager release];
}
위의 코드를 수행하게 되면 document에 데이터가 없다면 복사를 수행하라는 의미의 코드인듯 합니다.( 사실 이 부분은 아직 잘 모름 )
그래서 위의 함수를 적용 및 호출을 아래와 같이 해주니까.
제대로 데이터가 불러와 지더군요.
- (id) init
{
if (self = [super init])
{
touchPos = CGPointMake(0, 0);
gameState = kLogo;
logoBack = [[LogoBack alloc] init];
// Execute the "checkAndCreateDatabase" function
[self checkAndCreateDatabase];
// Query the database for all animal records and construct the "animals" array
[self readAnimalsFromDatabase];
}
return self;
}
위의 내용에 대해서 실제적인 코드는 여기 압축을 해서 올리지 못하지만,
sqlite3의 내용을 조금 숙지 하셨다면 금방 이해 하시리라 믿습니다. ^^
이거 가지고 조금 삽질을 했네요.
다행이 이 코드를 보면서 다른 면을 보게 되서 더 기쁘네요 ^^
Prev
Rss Feed