Wednesday, 28 December 2011

Adding Data to a server from the app-iPhone

//Adding username and password to a mysql table hosted in a server with two fields user and pass.


-(IBAction)AddData:(id)sender{
    NSURL *url = [NSURL URLWithString:@"http://sweans.org/test-saf/rss/"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    
    NSString* appendStr = [NSString stringWithFormat:@"user=%@&pass=%@",textUser.text,textPass.text];
    
    NSData *requestData = [appendStr dataUsingEncoding:NSUTF8StringEncoding];
    
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
    [theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [theRequest setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPBody: requestData];
    
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    
    if( theConnection )
    {
        responseData = [NSMutableData data];
    }
    else
    {
        NSLog(@"theConnection is NULL");
    }

    
    
}



-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [responseData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
    
   // NSLog(@"Data from server%@",responseData);
    
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"ERROR with theConenction");
   // [connection release];
  //  [responseData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"DONE. Received Bytes: %d", [responseData length]);
    NSString *theXML = [[NSString alloc] initWithBytes: [responseData mutableBytes] length:[responseData length] encoding:NSUTF8StringEncoding];
    NSLog(@"%@",theXML);
   // [theXML release];
}

No comments:

Post a Comment