我想從我的iPhone上傳圖片到我的網站,但我需要首先進行身份驗證。NSURLConnection,然後登錄發佈圖片
我的第一次嘗試是使用NSMutableURLRequest發送帶有我的登錄憑據的HTTP Post請求,然後以類似的方式使用第二個NSMutableURLRequest(在單獨的NSURLConnection中)發送圖像。但是失敗了,因爲沒有會話數據從登錄到圖像文章。第二次請求中仍然存在身份驗證錯誤。
我以爲我會很聰明,並創建一個隱藏的UIWebView,只需撥打[webview loadRequest:request];
登錄,然後張貼圖像,其中請求是NSMutableURLRequest
類型。這工作很好,現在我能夠上傳圖像到我的網站.....
....但是,當我嘗試在我的iPod touch上,我得到臭名昭着的received memory warning
,其次是應用程序崩潰時,我調用[webview loadRequest:request];
我只爲整個應用程序分配了大約10MB的內存(感謝探查器),所以我猜它不在請求本身中,而是UIWebView如何處理它。我認爲UIWebive的「視圖」部分正在分配大量內存。
以下是我的問題:如何在NSURLConnections之間持續保存會話和登錄數據,以便我不必使用UIWebView?
僞代碼:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:YES];
[request setTimeoutInterval:180];
[request setHTTPMethod:@"POST"];
[ request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
NSURL* url = [[NSURL alloc]initWithString:@"http://website.com/login.php"];
NSMutableData *body = [NSMutableData data];
[body appendData:[@"username=me&password=password&" dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setURL:url];
然後:
[self.webview loadRequest:request];
或者:
NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
NSLog(@"Login Opened");
responseData = [NSMutableData data];
} else {
NSLog(@"Logon failed");
}