2013年5月30日木曜日

[iOS]NSURLConnectionを使用してHTTP接続をする。

cookieの保存が必要だったのでメモを残しておく。

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //リクエストを作成
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setHTTPMethod:@"GET"];
    [request setURL:[NSURL URLWithString:@"http://apple.ios.sample.com"]];
    [request setTimeoutInterval:30.0];
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    
    //Cookieを保持している場合は読み込む
    //TODO Cookieの扱いがおかしい?
    NSHTTPCookie *cookie = nil;
    NSData *cookiesData = [[NSUserDefaults standardUserDefaults] objectForKey:@"cookie"];
    if (cookiesData.length != 0) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesData];
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    } else {
        //TODO Cookieが保持されていない
    }
    NSArray *cookieArray = [NSArray arrayWithObjects: cookie, nil];
    NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];
    [request setAllHTTPHeaderFields:headers];
    
    //ネットワーク接続を開始
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    [connection release];
    [request release];
}

#pragma mark -

//サーバーから認証の要求があった時に呼び出される
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    
}

//サーバーからレスポンスがあった時に呼び出される
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{   
    //Cookieを保存
    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:
                           [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
    [[NSUserDefaults standardUserDefaults] setObject:cookiesData
                                              forKey:@"cookie"];
    
    //レスポンスコード取得
    statusCode = [((NSHTTPURLResponse *)response) statusCode];
    
    if ([receivedData retainCount]) {
        [receivedData release];
    }
    receivedData = [[NSMutableData alloc] init];
}

//サーバーからデータを受け取ると呼び出される
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

//サーバーからの通信が終わる直前に呼び出される
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //TODO receivedDataにbodyが入っている
}

2013年5月14日火曜日

[iOS]Interface BuilderでUIScrollViewのContentSizeを設定することはできない。


Interface BuilderでUIScrollViewのContentSizeを設定使用と思ったが、
それを行うUIが無いことに気づいた。

http://stackoverflow.com/questions/1135163/how-do-i-use-uiscrollview-in-interface-builder
によると、ContentSizeはコード状態のみ設定可能のようだ、IBでやるのは諦めよう。
ただしiOS6のAuto Layoutを使用すれば可能になる。

With Autolayout (iOS6+), you can avoid setting contentSize. Set the following constraints instead:
Pin the top of the scrollview to the top of its top-most child.
And pin the bottom to the bottom of its bottom-most child.