错误域= NSURLErrorDomain代码= -1004“无法连接到服务器”。

时间:2017-08-10 07:41:37

标签: ios objective-c

我收到此错误:

  

错误域= NSURLErrorDomain代码= -1004“无法连接到   服务器。“UserInfo = {NSUnderlyingError = 0x600000250530 {错误   Domain = kCFErrorDomainCFNetwork Code = -1004“(null)”

以下是我的代码:

    -(NSMutableURLRequest*)createRequest:(NSURL*)url data:(NSData*)postData
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];  
    NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned 
                           long)[postData length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];
    [request setValue:@"application/x-www-form-urlencoded" 
        forHTTPHeaderField:@"Content-Type"];

    [request setURL:url];
    [request setHTTPMethod:@"POST"];

    return request;
}

-(void)requestForUserRegister:(NSString*)name password:(NSString*)password phone:(NSString*)phone email:(NSString*)email
{

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:3000/*******/"]];

    NSString *data = [NSString stringWithFormat:@"name=%@&password=%@&phone=%@&email=%@",name,password,phone,email];

    NSString *post =[data stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
   // NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
    NSMutableURLRequest *request = [self createRequest:url data:postData];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if(error)
        {
            [self.apiDelegate responseDidFail:self];
        }else
        {
            @try {
                self.value = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

                [self.apiDelegate responseDidSecceed:self];
            } @catch (NSException *exception) {

                [self.apiDelegate responseDidFail:self];
            }
        }

    }]
     resume];
  }

0 个答案:

没有答案