Подключение к серверу с помощью NSURLConnection target c - PullRequest
0 голосов
/ 30 сентября 2019

Я пытаюсь подключить свое приложение к бэкэнду, используя NSURLConnection.

Когда я использую почтальон, все работает очень хорошо, и я получаю ожидаемый результат.

Но когда я пытаюсь это сделать вВ моем коде я получаю совершенно другой результат, который является объектом JSON с сервера, но с сообщением об ошибке.

Пожалуйста, проверьте следующие изображения и код, который я использую, для получения более подробной информации. Любая идея будет по достоинству оценена.

enter image description here

enter image description here

enter image description here

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

NSString *urlStr=[NSString stringWithFormat:@"URL"];
NSURL* _url=[NSURL URLWithString:urlStr];
[request setURL:_url];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[request setValue:@"Bearer ---" forHTTPHeaderField:@"Authorization"];


NSArray *keys= [[NSArray alloc] initWithObjects:@"email",@"firebase_token",@"password",@"username",@"phone",@"uploaded_file", nil];
NSArray *values = [[NSArray alloc] initWithObjects:email,@"token",password,userName,phone,@"@/C:/Users/admin/Downloads/chili house.png", nil];
NSDictionary *params = [[NSDictionary alloc] initWithObjects:values forKeys:keys];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];
[request setHTTPBody:jsonData];

NSString *jsonString;
if ( jsonData) {
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

[request setHTTPBody:jsonData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

[connection start];
}

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
if ([challenge previousFailureCount] == 0) {

    NSURLCredential *newCredential;
    newCredential = [NSURLCredential credentialWithUser:@"User"
                                               password:@"Password"
                                            persistence:NSURLCredentialPersistenceNone];
    [[challenge sender] useCredential:newCredential
           forAuthenticationChallenge:challenge];
} else {
    [[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Connection failed: %@", [error description]);
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return YES;
    }
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [self.responseData setLength:0];

    }

- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
    return nil;
    }
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[[BusyAgent defaultAgent] makeBusy:NO];
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
if (responseString == (id)[NSNull null] || responseString.length == 0 ){
    NSLog(@"responseString= %@",responseString);
}else{
    NSLog(@"responseString = %@",responseString);
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:responseString delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
    [alert show];
}
self.responseData = nil;
}
...