错误域= NSURLErrorDomain

时间:2015-12-04 07:07:04

标签: ios objective-c post

我很抱歉这个问题。我是iOS新手。

我正在研究xcode 7.1。我在POST上拨打Local server来电,但我收到此错误。而且我不确定为什么。我一直在尝试和搜索几天,但我找不到任何相关的东西。这是我的代码

NSString *myUrlString = [NSString stringWithFormat:@"%@%@/login",link,Entry ];

//create string for parameters that we need to send in the HTTP POST body
    NSLog(@"My Url = %@",myUrlString);
    NSMutableDictionary* postRequestDictionary = [[NSMutableDictionary alloc] init];

    postRequestDictionary[@"email" ]= EmailIDTF.text;
    postRequestDictionary[@"password" ]= PasswordTF.text;


    NSLog(@"body = %@",postRequestDictionary);
    NSData *json;
    NSString *jsonString;
    NSError *error;

    // Dictionary convertable to JSON ?
    if ([NSJSONSerialization isValidJSONObject:postRequestDictionary])
    {
        // Serialize the dictionary
        json = [NSJSONSerialization dataWithJSONObject:postRequestDictionary options:NSJSONWritingPrettyPrinted error:&error];

        // If no errors, let's view the JSON
        if (json != nil && error == nil)
        {
            jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];

            NSLog(@"JSON: %@", jsonString);

        }
    }

    //create a mutable HTTP request
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[myUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
                                                              cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                          timeoutInterval:60.0];                //sets the receiver’s timeout interval, in seconds
    [urlRequest setTimeoutInterval:30.0f];
    //sets the receiver’s HTTP request method
    [urlRequest setHTTPMethod:@"POST"];



    [urlRequest addValue:@"application/json" forHTTPHeaderField:@"Content-type"];



    NSString *params = [NSString stringWithFormat:@"%@",jsonString];
    NSLog(@"param = %@",params);
    //sets the request body of the receiver to the specified data.
    [urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

    //allocate a new operation queue
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

  //Loads the data for a URL request and executes a handler block on an
    //operation queue when the request completes or fails.
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:queue
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error) {
         if ([data length] >0 && error == nil){
             //process the JSON response
             //use the main queue so that we can interact with the screen
             dispatch_async(dispatch_get_main_queue(), ^{
                 [self parseResponse1:data];
             });
         }
         else if ([data length] == 0 && error == nil){
             NSLog(@"Empty Response, not sure why?");
         }
         else if (error != nil){
             dispatch_async(dispatch_get_main_queue(), ^{
                 NSLog(@"Not again, what is the error = %@", error);
                 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Alert!" message:@"Please check that you are connected to internet." delegate:self cancelButtonTitle:@"I got it." otherButtonTitles: nil];
                 //                         spinnerview.hidden=YES;
                 [alert show];

             });

         }
     }];

但我得到的只是这个错误

  

错误域= NSURLErrorDomain代码= -1012"(null)" UserInfo = {NSErrorFailingURLKey = http://xyz/login,NSErrorFailingURLStringKey = http://xyz/login,NSUnderlyingError = 0x165a0f80 {错误域= kCFErrorDomainCFNetwork代码= -1012"(null)" UserInfo = {_ kCFURLErrorAuthFailedResponseKey = {url = http://xyz/login}}}}

事情是,它为什么要给予"(null)" ?? 请帮帮我们。提前致谢。

2 个答案:

答案 0 :(得分:0)

info.plist文件中添加此密钥后尝试:

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

希望这有帮助。

答案 1 :(得分:0)

pragma mark使用此代码调用Web服务

 NSString *myUrlString = [NSString stringWithFormat:@"%@%@/login",link,Entry ];      
NSMutableDictionary* postRequestDictionary = [[NSMutableDictionary alloc] init]; 
postRequestDictionary[@"email" ]= EmailIDTF.text;     
postRequestDictionary[@"password" ]= PasswordTF.text;



NSString *mystring=[self returnMeParameterString:postRequestDictionary];
NSURL *url = [NSURL URLWithString:myUrlString];

NSData *postData = [mystring dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[mystring length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse response, NSData data, NSError *connectionError) {

    if(connectionError)
    {
       //error
    }
    else
    {
       //success
    }
}];

pragma mark将Dictionary转换为字符串

 -(NSString*)returnMeParameterString:(NSDictionary *)params{

NSMutableString *paramstring = [[NSMutableString alloc] init];

NSMutableArray *keyArray = [[NSMutableArray alloc] init];

NSMutableArray *valueArray = [[NSMutableArray alloc] init];

for( NSString *aKey in [params allKeys] )
{
    [keyArray addObject:aKey];
}

for( NSString *aValue in [params allValues] )
{
    [valueArray addObject:aValue];
}

for (int k=0; k< keyArray.count; k++)
{
    NSString *tempString;

    if(k==0)
    {
        tempString = [NSString stringWithFormat:@"%@=%@",[keyArray objectAtIndex:k],[valueArray objectAtIndex:k]];
    }
    else
    {
        tempString = [NSString stringWithFormat:@"&%@=%@",[keyArray objectAtIndex:k],[valueArray objectAtIndex:k]];
    }

    [paramstring appendString:tempString];

}

return paramstring;
}