Ответ 1
Загрузите фреймворк по ссылке ниже. Затем я собрал код, который отправляет электронное письмо с приятным "пожалуйста, подождите". Я прикрепил изображение того, как это выглядит во время его работы (за несколько секунд). Обратите внимание: я не беру на себя ответственность за создание структуры SMTP. Он был загружен из Интернета после его поиска навсегда. Zip файл, который вы можете скачать, включает в себя оверлейные изображения, которые я создал для отзывов пользователей. Он имеет как @2x, так и обычный. Вам нужно будет войти в конструктор интерфейсов и создать ярлык, хотя он говорит "отправка тестового диска..". Его уже в коде, но я не добавил его из кода. Поэтому вы должны добавить его в IB.
1. Обязательно добавьте фреймворк, который вы загруженный в ваш проект.
2. Обязательно добавьте фреймворк CFNetwork в свой проект
3. Обязательно присоединяйте имя UILabel "loadLabel" в построителе интерфейсов
4. Имя пользователя и пароль, которые код ссылается на smtp сервер. Если у вас нет одного учетную запись gmail и использование gmail Настройки. Если вы не знакомы с настройками gmail google "gmail smtp" вы найдете то, что вам нужно.
Найти структуру и искусство здесь
Для вашего .h файла обязательно включите:
//for sending email alert
UIActivityIndicatorView * spinner;
UIImageView * bgimage;
IBOutlet UILabel * loadingLabel;
}
@property (nonatomic, retain)IBOutlet UILabel * loadingLabel;
@property (nonatomic, retain)UIImageView * bgimage;
@property (nonatomic, retain)UIActivityIndicatorView * spinner;
-(void)sendEmail;
-(void)removeWaitOverlay;
-(void)createWaitOverlay;
-(void)stopSpinner;
-(void)startSpinner;
Для вашего .m файла:
@synthesize bgimage,spinner,loadingLabel;
// add this in ViewDidLoad
//set loading label to alpha 0 so its not displayed
loadingLabel.alpha = 0;
все остальное - это его собственная функция
-(void)sendEmail {
// create soft wait overlay so the user knows whats going on in the background.
[self createWaitOverlay];
//the guts of the message.
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
testMsg.fromEmail = @"[email protected]";
testMsg.toEmail = @"[email protected]";
testMsg.relayHost = @"smtpout.yourserver.net";
testMsg.requiresAuth = YES;
testMsg.login = @"[email protected]";
testMsg.pass = @"yourPassWord";
testMsg.subject = @"This is the email subject line";
testMsg.wantsSecure = YES; // smtp.gmail.com doesn't work without TLS!
// Only do this for self-signed certs!
// testMsg.validateSSLChain = NO;
testMsg.delegate = self;
//email contents
NSString * bodyMessage = [NSString stringWithFormat:@"This is the body of the email. You can put anything in here that you want."];
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/plain",kSKPSMTPPartContentTypeKey,
bodyMessage ,kSKPSMTPPartMessageKey,@"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,nil];
[testMsg send];
}
- (void)messageSent:(SKPSMTPMessage *)message
{
[message release];
//message has been successfully sent . you can notify the user of that and remove the wait overlay
[self removeWaitOverlay];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message Sent" message:@"Thanks, we have sent your message"
delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
[message release];
[self removeWaitOverlay];
NSLog(@"delegate - error(%d): %@", [error code], [error localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Email Error" message:@"Sending Failed - Unknown Error :-("
delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
-(void)createWaitOverlay {
// fade the overlay in
loadingLabel = @"Sending Test Drive...";
bgimage = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,480)];
bgimage.image = [UIImage imageNamed:@"waitOverLay.png"];
[self.view addSubview:bgimage];
bgimage.alpha = 0;
[bgimage addSubview:loadingLabel];
loadingLabel.alpha = 0;
[UIView beginAnimations: @"Fade In" context:nil];
[UIView setAnimationDelay:0];
[UIView setAnimationDuration:.5];
bgimage.alpha = 1;
loadingLabel.alpha = 1;
[UIView commitAnimations];
[self startSpinner];
[bgimage release];
}
-(void)removeWaitOverlay {
//fade the overlay out
[UIView beginAnimations: @"Fade Out" context:nil];
[UIView setAnimationDelay:0];
[UIView setAnimationDuration:.5];
bgimage.alpha = 0;
loadingLabel.alpha = 0;
[UIView commitAnimations];
[self stopSpinner];
}
-(void)startSpinner {
spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
spinner.hidden = FALSE;
spinner.frame = CGRectMake(137, 160, 50, 50);
[spinner setHidesWhenStopped:YES];
[self.view addSubview:spinner];
[self.view bringSubviewToFront:spinner];
[spinner startAnimating];
}
-(void)stopSpinner {
[spinner stopAnimating];
[spinner removeFromSuperview];
[spinner release];
}
Окончательные результаты показаны ниже. Экран немного тускнеет (например, когда отображается UIAlert). Он показывает сообщение о том, что он отправляется, а затем "улучшает" резервную копию при отправке сообщения.
Счастливое кодирование!!