Проблема с push-уведомлениями для городских дирижаблей - PullRequest
0 голосов
/ 06 июня 2011

Я занимаюсь разработкой приложения с телефонной пробкой, однако я пытаюсь сгенерировать вызов Push-уведомления через плагин с NSUrlconnection.

Уведомление работает со следующей командой curl -X POST -u ":" -H "Content-Тип: application / json "--data '{" device_tokens ": [" "]," aps ": {" alert ":" Vikrant сказать привет! "," Badge ":" 5 "}}' https://go.urbanairship.com/api/push/

ТЕПЕРЬ Я ТЕБЕ ЖЕ С НИЖЕ КОДОМ

NSString *URL = @"https://go.urbanairship.com/api/push/";
    NSMutableURLRequest *req = [[[NSMutableURLRequest alloc] init] autorelease];

    [req setURL:[NSURL URLWithString:URL]];


    [req setHTTPMethod:@"POST"];

    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"application/json; boundary=%@",boundary];

    [req addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithString:@"{\"device_tokens\": [\"<devce token>\"], \"aps\": {\"alert\": \"Vikrant say Hello!\",\"badge\": \"5\"}}"] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];


    [req setHTTPBody:body];

    NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];
    finished = NO;
    finishedWithError = NO;
    if(xmlData == nil)
        [xmlData release];
    if(conn)
    {
        xmlData = [[NSMutableData alloc] retain];
        while(!finished)
        {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }
    }

Итак, это HTTPS URL с аутентификацией сервера .Итак, я написал делегатам.

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge: (NSURLAuthenticationChallenge *)challenge 
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
    {
        NSLog(@"Trust Challenge Requested!");
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
        [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];

    }
    else if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic])
    {
    NSLog(@"HTTP Auth Challenge Requested!");
        NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:@"<apikey>" password:@"<master key>" persistence:NSURLCredentialPersistenceForSession];
        [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
        [credential release];
    }


}

Проблема в том, что соединение не принимает имя пользователя и пароль.потому что печатает ниже вывода

2000-01-01 11:07:09.-540 WIPT[500:307] From APN
[Switching to thread 13059]
2000-01-01 11:07:13.-986 WIPT[500:307] Trust Challenge Requested!
2000-01-01 11:07:14.-82 WIPT[500:307] didReceiveResponse
2000-01-01 11:07:14.-25 WIPT[500:307] connection
2000-01-01 11:07:14.-05 WIPT[500:307] connectionDidFinishLoading
2000-01-01 11:07:15.-958 WIPT[500:307] APN response data Authorization Required

Это означает, что он выполняет URL, но не отправляет имя пользователя и пароль.Кто-нибудь знает решение

Ответы [ 2 ]

3 голосов
/ 06 июня 2011

Вызовы Push API обычно аутентифицируются с помощью мастер-секрета в качестве пароля, а не секрета приложения .Рассматривайте секрет приложения как код с ограниченным доступом, который можно безопасно встроить в приложение;вы никогда не вставите главный секрет в ваше приложение.

Однако, чтобы сделать доступным некоторое подмножество push-вызовов без главного секрета, вы можете включить флаг allow push from device наПриложение городского дирижабля.Это позволяет делать push-вызовы непосредственно на токен устройства с секретом приложения.Это не позволит вам использовать псевдонимы, теги или делать полные трансляции, так как они могут быть угаданы или могут стоить вам много хлопот.

АдамГородской дирижабль

1 голос
/ 01 августа 2011

Заменить NSURLAuthenticationMethodServerTrust на NSURLAuthenticationMethodHTTPBasic в canAuthenticateAgainstProtectionSpace делегат.

делегат.
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
 return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic];
}
...