天天看點

iPhone 天氣預報 Ojbective-c開發例子 主要實作檔案

//

//  WeatherReportViewController.m

//  WeatherReport

//

//  Created by a a on 10-7-22.

//  Copyright a 2010. All rights reserved.

//

//#import "WeatherLoadViewController.h"

#import "WeatherReportViewController.h"

static NSString *const urlAddr = @"http://www.webxml.com.cn/WebServices/WeatherWebService.asmx"; //連接配接位址

@implementation WeatherReportViewController

@synthesize city;

@synthesize hlTemperature;

@synthesize weather;

@synthesize windyDirection;

@synthesize tempString;

@synthesize weatherImageView1;

@synthesize weatherImageView2;

@synthesize currentWeather;

@synthesize timeLabel;

@synthesize tomorrowWeather;

@synthesize tomorrowTemperature;

@synthesize tomorrowWindy;

@synthesize tomorrowImage1;

@synthesize tomorrowImage2;

@synthesize afterTomorrowWeather;

@synthesize afterTomorrowtemperature;

@synthesize afterTomorrowWindy;

@synthesize afterTomorrowImage1;

@synthesize afterTomorrowImage2;

@synthesize weatherQueryField;

@synthesize downloadView;

@synthesize activityindicator;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

[super viewDidLoad];

[activityindicator startAnimating];

NSLog(@"updateWeather");

[self connectionWebService];

}

//連接配接伺服器

- (void) connectionWebService {

weatherData = [[NSMutableData alloc] init];

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

soapMessage = [NSMutableString 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"

  "<getWeatherbyCityName xmlns=/"http://WebXml.com.cn//">/n"

  "<theCityName>%@</theCityName>/n"

  "</getWeatherbyCityName>/n"

  "</soap:Body>/n"

  "</soap:Envelope>/n",self.queryWeather];

//建立連接配接

NSURL *url = [NSURL URLWithString:urlAddr];

NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];

NSString *soapmLength = [NSString stringWithFormat: @"%d", [soapMessage length]];

//post方式送出資料

[theRequest addValue: @"text/xml;charset=utf-8" forHTTPHeaderField:@"Content-Type"];

[theRequest addValue: @"http://WebXml.com.cn/getWeatherbyCityName" forHTTPHeaderField:@"SOAPACtion"];

[theRequest addValue: soapmLength forHTTPHeaderField: @"Content-Length"];

[theRequest setHTTPMethod: @"POST"];

[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

//[soapMessage release];

//NSURLConnection于伺服器互動

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest: theRequest

  delegate:self];

[connection release];

NSLog(@"%d", [weatherData retainCount]);

NSLog(@"%d", [soapMessage retainCount]);

}

//給NSXMLParser指派函數,開始解析xml

- (void) startParsingWeather {

NSLog(@"startParsingWeather");

NSXMLParser *parser = [[NSXMLParser alloc] initWithData:weatherData];

[parser setDelegate:self];

[parser setShouldProcessNamespaces:YES];

[parser setShouldResolveExternalEntities: YES];

NSError *parseError = [parser parserError] ;

//parseError = [parser parserError];

    if (parseError) {

        NSLog(@"parser parserError");

    }

[parser parse];

[parser release];

}

#pragma mark NSURLConnection

//收到伺服器回答

- (void) connection:(NSURLConnection*) conneciton

 didReceiveResponse:(NSURLResponse*) response {

NSLog(@"connection:didReceiveResponse:");

}

//接收資料

- (void) connection: (NSURLConnection*) conneciton

didReceiveData: (NSData*) data {

NSLog(@"connection:didReceiveData:");

[weatherData appendData: data];

}

//完成資料下載下傳

- (void) connectionDidFinishLoading: (NSURLConnection*) conneciton {

NSLog(@"connectionDidFinishLoading:");

[self startParsingWeather];

}

//錯誤處理

- (void) conneciton: (NSURLConnection*) conneciton

   didFailWithError:(NSError*) error {

NSLog(@"conneciton:didFailWithError:");

UIAlertView *errorAlert = [[UIAlertView alloc] 

  initWithTitle:[error localizedDescription]

  message:[error localizedFailureReason]

  delegate:nil cancelButtonTitle:@"OK"

  otherButtonTitles:nil];

[errorAlert show];

[errorAlert release];

}

#pragma mark NSXMLParser

//初始化數組

- (void) parserDidStartDocument: (NSXMLParser*) parser {

NSLog(@"parserDidStartDocument");

weatherArray = [[NSMutableArray alloc] init];

}

//紀錄元素開始标簽,并出始化臨時數組

- (void)parser:(NSXMLParser *)parser 

didStartElement:(NSString *)elementName 

  namespaceURI:(NSString *)namespaceURI 

 qualifiedName:(NSString *)qualifiedName 

attributes:(NSDictionary *)attributeDict {

if([elementName isEqualToString:@"string"]) {

if(!tempString) {

tempString = [[NSMutableString alloc] init];

}

}

}

//提取XML标簽中的元素,反複取多次

- (void) parser: (NSXMLParser*) parser

foundCharacters:(NSString*) string {

NSLog(@"parser: foundCharacters:");

if(tempString) {

[tempString appendString:string];

}

}

//紀錄元素結尾标簽,并把臨時數組中的元素存到字元串數組中

- (void)parser:(NSXMLParser *)parser 

 didEndElement:(NSString *)elementName 

  namespaceURI:(NSString *)namespaceURI 

 qualifiedName:(NSString *)qName {

if([elementName isEqualToString:@"string"])

{

[weatherArray addObject: tempString];

[tempString release];

tempString = nil;

}

}

//結束分析,調用顯示函數

- (void) parserDidEndDocument: (NSXMLParser*) parser {

NSLog(@" parserDidEndDocument:");

NSLog(@"%@",[weatherArray objectAtIndex:0]);

[self displayView];

}

#pragma mark displayView

//顯示界面函數

- (void) displayView {

[activityindicator stopAnimating];

city.text = [weatherArray objectAtIndex:1];

hlTemperature.text =  [weatherArray objectAtIndex:5];

weather.text =  [weatherArray objectAtIndex:6];

windyDirection.text = [weatherArray objectAtIndex:7];

weatherImageView1.image = [UIImage imageNamed:[NSMutableString stringWithFormat:@"b_%@",[weatherArray objectAtIndex:8]]];

weatherImageView2.image = [UIImage imageNamed:[NSMutableString stringWithFormat:@"b_%@",[weatherArray objectAtIndex:9]]];

currentWeather.font = [UIFont fontWithName: @"Arial" size: 14.0];  

currentWeather.lineBreakMode = UILineBreakModeWordWrap;

currentWeather.numberOfLines = 0;

currentWeather.text = [weatherArray objectAtIndex:10];

tomorrowTemperature.text =  [weatherArray objectAtIndex:12];

tomorrowWeather.text =  [weatherArray objectAtIndex:13];

tomorrowWindy.text = [weatherArray objectAtIndex:14];

tomorrowImage1.image = [UIImage imageNamed:[weatherArray objectAtIndex:15]];

tomorrowImage2.image = [UIImage imageNamed:[weatherArray objectAtIndex:16]];

afterTomorrowtemperature.text =  [weatherArray objectAtIndex:17];

afterTomorrowWeather.text =  [weatherArray objectAtIndex:18];

afterTomorrowWindy.text = [weatherArray objectAtIndex:19];

afterTomorrowImage1.image = [UIImage imageNamed:[weatherArray objectAtIndex:20]];

afterTomorrowImage2.image = [UIImage imageNamed:[weatherArray objectAtIndex:21]];

timeLabel.text = [weatherArray objectAtIndex:4];

downloadView.hidden = YES;

}

#pragma mark Query

//傳回查詢城市代碼字元串

- (NSString*) queryWeather {

return weatherQueryField.text;

}

//查詢按鈕處理函數,包括關閉鍵盤

- (IBAction) queryBegain {

downloadView.hidden = NO;

[weatherQueryField resignFirstResponder];

[self connectionWebService];

}

//按Return鍵,關閉鍵盤,在頭檔案裡定義UITextFieldDelegate委托,

//并把檔案輸入編輯框委托給file's owner

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

if(textField == weatherQueryField)

{

[self queryBegain];

}

return YES;

}

#pragma mark Finish

- (void)didReceiveMemoryWarning {

// Releases the view if it doesn't have a superview.

    [super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.

}

- (void)viewDidUnload {

// Release any retained subviews of the main view.

// e.g. self.myOutlet = nil;

}

- (void)dealloc {

    [super dealloc];

//[soapMessage dealloc];

}

@end