0
我正在向服務器發送一個請求,返回一個字符串,即如果用戶存在或不與該暱稱,發佈通知工作完美,並打印出來返回的結果從完成處理程序內的下1秒,但它需要額外的17至20爲基於返回的結果中的圖片設置圖像後retreaving一個post請求的結果需要17s
這裏是我使用的代碼:
- (void)textFieldDidBeginEditing:(UITextField *)textField{
// for each textfield selected checkl previous text field formating
if (textField == registerEmailAddressTextField)
{
//check if nickname is at least 6 charactes
if (registerNicknameTextField.text.length < 6) {
NSLog(@"EMIAL TEXT FIELD");
[registerNicknameCheckmarkLabel setImage:[UIImage imageNamed:@"wrong_checkmark.png"]];
}else{
NSLog(@"checking nickname");
//check if nickname exists or not
NSURL *url = [NSURL URLWithString:@"myURL"];
//Create the session with custom configuration
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";
NSError *error = nil;
NSString* str = [NSString stringWithFormat:@"username=%@", registerNicknameTextField.text];
NSData* jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
[request setValue:[NSString stringWithFormat:@"%d", (int)registerNicknameTextField.text.length] forHTTPHeaderField:@"Content-Length"];
if (!error) {
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:jsonData completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString* result2 = [responseString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *secondString = [result2 stringByReplacingOccurrencesOfString:@" " withString:@""];
if ([secondString isEqualToString:@"exist"]) {
NSLog(@"nickname allready exists");
[registerNicknameCheckmarkLabel setImage:[UIImage imageNamed:@"wrong_checkmark.png"]];
}else{
[registerNicknameCheckmarkLabel setImage:[UIImage imageNamed:@"correct_checkmark.png"]];
NSLog(@"nickname doesn't exists");
}
}];
[uploadTask resume];
}
}
}
}
我甚至試過沒有成功,強制刷新屏幕使用這些代碼:
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW,
(int64_t)(0.005 * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
[self.view setNeedsDisplay];
});
你應該嘗試派遣你的'setImage:'調用到主線程。我認爲'completionHandler'被後臺隊列調用。 – dan 2015-04-01 18:04:06
除主線程外,不要在任何地方進行UI更改。嘗試使用GCD檢索主線程並在其上運行代碼。它可能不會改變任何事情,但這是一個好習慣。出於好奇,形象有多大? – 2015-04-01 18:15:02
如果我理解正確'nickname allready exists'會很快記錄下來,但是圖片需要一些時間才能真正出現 - 即網絡代碼全部完成,但是從調用' [registerNicknameCheckmarkLabel setImage:[UIImage imageNamed: @「wrong_checkmark.png」]];'看到圖像出現..是這樣嗎? – button 2015-04-01 18:19:07