无法在另一种方法ios中使用nsurlconnection

时间:2013-11-22 09:31:04

标签: ios nsurlconnection nsurlrequest

我在我的应用程序中使用了以下方式的NSURLConnection。但是当我尝试在同一个类的另一个方法中执行相同操作时,连接不会建立。我没有收到任何错误。调试时,我看到该程序没有进入下面的代码。请帮忙。

编辑:

if ([self hasInternetConnection] || [self hasWiFi] || [self canReachHost:@"http://myservice.asmx"]) {
        NSLog(@"Refreshing...");

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *defaultPhoneNumber = [defaults objectForKey:@"PhoneNumber"];

        NSString *xmlString = [NSString stringWithFormat:@"<ServiceCalls><ServiceCall><Phone_No>%@</Phone_No></ServiceCall></ServiceCalls>", defaultPhoneNumber];
        xmlString = [xmlString stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"];
        xmlString = [xmlString stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];

        NSLog(@"%@", xmlString);

        //NSString *xmlString = @"&lt;?xml version=\"1.0\"?&gt;&lt;ServiceCalls&gt;&lt;ServiceCall&gt;&lt;Phone_No&gt;03102497593&lt;/Phone_No&gt;&lt;/ServiceCall&gt;&lt;/ServiceCalls&gt;";

        NSString *soapMessage = [NSString stringWithFormat:
                                 @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                                 "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                                 "<soap:Body>\n"
                                 "<GetVehiclesByPhone_ServiceCall_Proc xmlns=\"http://tempuri.org/\">\n"
                                 "<xmlStr>%@</xmlStr>\n"
                                 "<m_LoginId>%@</m_LoginId>\n"
                                 "<m_pass>%@</m_pass>\n"
                                 "</GetVehiclesByPhone_ServiceCall_Proc>\n"
                                 "</soap:Body>\n"
                                 "</soap:Envelope>\n", xmlString, @"User", @"pass"];

        NSLog(@"soapMessage: \n%@",soapMessage);

        NSURL *url = [NSURL URLWithString:@"http://myservice.asmx"];
        NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
        NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];

        [request1 addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [request1 addValue:@"http://tempuri.org/GetVehiclesByPhone_ServiceCall_Proc" forHTTPHeaderField:@"SOAPAction"];
        [request1 addValue:msgLength forHTTPHeaderField:@"Content-Length"];
        [request1 setHTTPMethod:@"POST"];
        [request1 setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];

        NSLog(@"%@", request1);

        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [NSURLConnection sendAsynchronousRequest:request1 queue:queue completionHandler:^(NSURLResponse *response, NSData *data1, NSError *error) {

            if (data1 != nil) {
                if ([data1 length] > 0 && error == nil) {
                    NSString *theXML = [[NSString alloc] initWithBytes:[data1 bytes] length:[data1 length] encoding:NSUTF8StringEncoding];
                    theXML = [theXML stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
                    theXML = [theXML stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
                    NSLog(@"THE XML= %@",theXML);
                    NSData *receivedData = [theXML dataUsingEncoding:NSUTF8StringEncoding];

                    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:receivedData];
                    xmlParser.delegate = (id)self;
                    [xmlParser parse];

                    NSString *delete = [NSString stringWithFormat:@"DELETE FROM Vehicles"];

                    char *err;

                    if (sqlite3_exec(db, [delete UTF8String], NULL, NULL, &err) == SQLITE_OK) {
                        for (NSObject *currentObject in entries) {
                            NSLog(@"Entries: %@", [currentObject valueForKey:@"vrn"]);
                            NSString *insert = [NSString stringWithFormat:@"INSERT INTO Vehicles VALUES ('%@', '%@', '%@' , '%@')", [currentObject valueForKey:@"vrn"], [currentObject valueForKey:@"make"], [currentObject valueForKey:@"model"], [currentObject valueForKey:@"yearMade"]];
                            if (sqlite3_exec(db, [insert UTF8String], NULL, NULL, &err) != SQLITE_OK) {
                                sqlite3_close(db);
                                NSAssert(0, @"Could not update table");
                                [defaults setInteger:0 forKey:@"DataExists"];
                            }
                            else {
                                [defaults setInteger:1 forKey:@"DataExists"];
                                NSLog(@"Table updated");
                            }
                        }
                    }
                    else {
                        sqlite3_close(db);
                        NSAssert(0, @"Could not delete records");
                    }
                    [entries removeAllObjects];

                    [vrnTable performSelectorOnMainThread:@selector(reloadData) withObject:self waitUntilDone:YES];

                    NSString *select = [NSString stringWithFormat:@"SELECT * FROM Vehicles"];
                    sqlite3_stmt *statement;

                    if (sqlite3_prepare_v2(db, [select UTF8String], -1, &statement, nil) == SQLITE_OK) {
                        while (sqlite3_step(statement) == SQLITE_ROW) {
                            vehicleObject = [[Vehicle alloc] init];
                            char *vrn = (char *) sqlite3_column_text(statement, 0);
                            NSString *vrnStr = [[NSString alloc] initWithUTF8String:vrn];
                            vehicleObject.vrn = vrnStr;

                            char *make = (char *) sqlite3_column_text(statement, 1);
                            NSString *makeStr = [[NSString alloc] initWithUTF8String:make];
                            vehicleObject.make = makeStr;

                            char *model = (char *) sqlite3_column_text(statement, 2);
                            NSString *modelStr = [[NSString alloc] initWithUTF8String:model];
                            vehicleObject.model = modelStr;

                            char *yearMade = (char *) sqlite3_column_text(statement, 3);
                            NSString *yearMadeStr = [[NSString alloc] initWithUTF8String:yearMade];
                            vehicleObject.yearMade = yearMadeStr;

                            [entries addObject:vehicleObject];
                        }
                    }
                    else {
                        NSAssert1(0, @"Error: Because %s", sqlite3_errmsg(db));
                    }

                    [self.vrnTable performSelector:@selector(reloadData) onThread:[NSThread mainThread] withObject:self waitUntilDone:YES];
                    //[self removeLodingView];
                }
                else {
                    [self invalidAlert];
                }
            }
            else {
                [self invalidAlert];
            }
        }];
    }
    else {
        [self noNetworkAlert];
    }
    [_vrnTableViewController.refreshControl endRefreshing];

1 个答案:

答案 0 :(得分:0)

检查所有条件

[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
    {
        NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
            NSLog(@"responseCode: %d", responseCode);  //check response code

        if ([data length] > 0 && error == nil)

          //data downloaded -> continue

        else if ([data length] == 0 && error == nil)
            //empty reply
        else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
           // time out
        else if (error != nil)
            //error
    }];