通过RESTful WCF服务从iPhone应用程序访问SQL数据库

时间:2014-01-04 21:41:07

标签: ios iphone sql wcf web-services

我创建了一个小项目,可以通过RESTful WCF服务从iPhone读取数据并将数据插入到SQL服务器中。

我已使用以下方法成功读取数据:

1-我创建了一个wcf Web服务,它从表的Employees(firstname,lastname,salary)读取Sql server中的数据:

"41.142.251.142/JsonWcfService/GetEmployees.svc/json/employees"

2-我在xcode 5.0.2中创建了一个新项目,并添加了一个textfield(viewData.text)来显示Web服务检索的数据。 3-我在viewController.m中添加了以下指令:

    "#define WcfSeviceURL [NSURL URLWithString: @"41.142.251.142/JsonWcfService/GetEmployees.svc/json/employees"]"

3- In(void)viewDidLoad方法,我实现了以下代码:

     - (void)viewDidLoad
{
    [super viewDidLoad];
    NSError *error = nil;
    NSData *data = [NSData dataWithContentsOfURL:WcfSeviceURL options:NSDataReadingUncached error:&error];

    if(!error)
    {
        NSDictionary* json = [NSJSONSerialization 
                              JSONObjectWithData:data 
                              options:NSJSONReadingMutableContainers 
                              error:&error];  

        NSMutableArray *array= [json objectForKey:@"GetAllEmployeesMethodResult"];

        for(int i=0; i< array.count; i++)
        {
            NSDictionary *empInfo= [array objectAtIndex:i];

            NSString *first = [empInfo objectForKey:@"firstname"];
            NSString *last = [empInfo objectForKey:@"lastname"];
            NSString *salary  = [empInfo objectForKey:@"salary"];

            //Take out whitespaces from String
            NSString *firstname = [first
                                   stringByReplacingOccurrencesOfString:@" " withString:@""];
            NSString *lastname = [last
                                   stringByReplacingOccurrencesOfString:@" " withString:@""];

            viewData.text= [viewData.text stringByAppendingString:[NSString stringWithFormat:@"%@ %@ makes $%@.00 per year.\n",firstname,lastname,salary]];
        }

    }
}

检查以下链接:http://www.codeproject.com/Articles/405189/How-to-access-SQL-database-from-an-iPhone-app-Via

正如我所提到的,我可以毫无问题地从我的iPhone上读取数据。

所以第二步是如何将数据从iPhone写入和插入到SQL Server。 为此,我首先创建了在我的webservice中插入数据的方法:

在WCF界面中:

    [OperationContract]
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "json/InsertEmployee/{id1}/{id2}/{id3}")]
    bool InsertEmployeeMethod(string id1,string id2, string id3);

在实施中:

      public bool InsertEmployeeMethod(string id1,string id2, string id3)
   {

       int success = 0;

       using (SqlConnection conn = new SqlConnection("server=(local);database=EmpDB;Integrated Security=SSPI;"))
       {
           conn.Open();

           decimal value= Decimal.Parse(id3);
           string cmdStr = string.Format("INSERT INTO EmpInfo VALUES('{0}','{1}',{2})",id1,id2,value);
           SqlCommand cmd = new SqlCommand(cmdStr, conn);
           success = cmd.ExecuteNonQuery();

           conn.Close();
       }

       return (success != 0 ? true : false);
   }

所以要测试这个web servcie方法,请使用:

"41.142.251.142/JsonWcfService/GetEmployees.svc/json/InsertEmployee/myName/MylastName/6565"

然后从iPhone使用此方法我使用了以下方法:  我宣布了定义指令:

"#define BaseWcfUrl [NSURL URLWithString: 
@"41.142.251.142/JsonWcfService/GetEmployees.svc/json/InsertEmployee/{id1}/{id2}/{id3}"]"

然后我实现了与点击按钮相关的插入员工方法。

      -(void) insertEmployeeMethod

{

if(firstname.text.length && lastname.text.length && salary.text.length)

{

    NSString *str = [BaseWcfUrl stringByAppendingFormat:@"InsertEmployee/%@/%@/%@",firstname.text,lastname.text,salary.text];

    NSURL *WcfServiceURL = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [request setURL:WcfServiceURL];

    [request setHTTPMethod:@"POST"];

    // connect to the web

    NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    // NSString *respStr = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];


    NSError *error;

    NSDictionary* json = [NSJSONSerialization 

                          JSONObjectWithData:respData 

                          options:NSJSONReadingMutableContainers 

                          error:&error];  



    NSNumber *isSuccessNumber = (NSNumber*)[json objectForKey:@"InsertEmployeeMethodResult"];

//创建一些标签字段以显示状态

        status.text = (isSuccessNumber && [isSuccessNumber boolValue] == YES) ? [NSString stringWithFormat:@"Inserted %@, %@",firstname.text,lastname.text]:[NSString stringWithFormat:@"Failed to insert %@, %@",firstname.text,lastname.text];
    }

}

但问题在于以下说明:

 NSString *str = [BaseWcfUrl stringByAppendingFormat:@"InsertEmployee/%@/%@/%@",firstname.text,lastname.text,salary.text];

系统始终使用此行返回消息'数据参数nil',知道firstname.text和lastname.text,salary都已填充,我可以使用{{{{{ 1}}

你能帮忙吗? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

我认为NSURLs stringByAppendingFormat不会做你想要的。

尝试这样的事情:

#define kBase_URL                @"41.142.251.142/JsonWcfService/GetEmployees.svc/json/%@"

#define kAuthAPI_InsertEmployee_URL   [NSString stringWithFormat:kBase_URL, @"InsertEmployee/%@/%@/%@"]

//Setup session
NSError *error;
NSURL *requestURL = [NSURL URLWithString:[NSString stringWithFormat:kAuthAPI_InsertEmployee_URL,firstname.text,lastname.text,salary.text]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];

NSData *postData = [NSJSONSerialization dataWithJSONObject:profileData options:0 error:&error];
[request setHTTPBody:postData];

etc. etc.