iOS與Web Service(Php)資料交換
概念圖 |
與webService(php),利用Json進行資料交換,這邊是沿續Web Service(PHP、MySQL、JSON),繼續說明iOS處理如何Json |
Json格式,像是Dictionary Key-Value組成 |
定義巨集 |
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1 #define kWSLookingFunURL [NSURL URLWithString:@"http://localhost/wsCatalog.php"] |
從web Service讀取資料 |
//讀取web service -(void)wsLookingFun { dispatch_async(kBgQueue, ^{ NSData *data = [NSData dataWithContentsOfURL:kWSLookingFunURL]; [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; }); } //讀取後的資料處理 -(void)fetchedData:(NSData*)responseData { NSError *error = nil; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; NSArray *catalogs_ = [json objectForKey:@"catalogs"]; //NSString *jsonFormat = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding]; //NSLog(@"HTML = %@", jsonFormat); catalogData_ = [NSArray arrayWithArray:catalogs_]; [self.tableView reloadData]; } |
顯示在UITableView上 |
//UITableView資料顯示
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellId = @"cell"; UITableViewCell *cell; cell = [tableView dequeueReusableCellWithIdentifier:cellId]; if (cell==nil) { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId]; } //catalogData_為陣列,利用indexPath.row將元素取出,放到Dictionary /* 資料格式 catalog = { description = ""; id = "\U7f8e\U5f0f\U9910\U5ef3"; timestamp = "2012-03-13 00:59:37"; }; */ NSDictionary *catalog_ = [catalogData_ objectAtIndex:indexPath.row]; NSLog(@"%@",catalog_); cell.textLabel.text = [[(NSDictionary*)catalog_ objectForKey:@"catalog"]objectForKey:@"id"]; cell.detailTextLabel.text = [[(NSDictionary*)catalog_ objectForKey:@"catalog"]objectForKey:@"timestamp"]; return cell; } |
資料寫入:先將資料轉為Json格式後,再POST到Web service |
//資料新增(產生Json的格式)
- (IBAction)insertCatalog:(id)sender { NSError *error = NULL;
NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys: [txtCatalog_ text],@"id", @"from iphone",@"description" , nil]; //壓縮成NSData,這時的編碼會成UTF8格式 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:info options:NSJSONWritingPrettyPrinted error:&error]; //完成Json格式後,進行新增 [self insertCatalogWithJson:jsonData];
} //傳送至web Service -(void)insertCatalogWithJson:(NSData*)json {
NSString *urlAsString = [[NSString alloc]initWithString: [kWSLookingFunURL absoluteString]]; urlAsString = [urlAsString stringByAppendingString:@"?action=insert"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setTimeoutInterval:30.0f]; [urlRequest setHTTPMethod:@"POST"]; //直接把NSData(這時的編碼為UTF8)做為傳送的內容 [urlRequest setHTTPBody:json]; NSLog(@"REQUEST: %@", [urlRequest HTTPBody]); NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if ([data length] >0 && error == nil) { NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"HTML = %@", html); //重新從WebService讀取資料 [self wsLookingFun]; }else if ([data length] == 0 && error == nil) { NSLog(@"Nothing was downloaded."); } else if (error != nil) { NSLog(@"Error happened = %@", error); }}]; } |