2010-07-18 84 views
1

我爲iPhone寫了一個gps應用程序,它一切正常,但現在我想通過互聯網使用最簡單的方式將經緯度發送到服務器...我有一個來自服務器的URL是緯度和經度的參數。我也想要拉特。和長。每90秒左右發送一次。這一切究竟如何?任何幫助非常感謝,提前感謝!使用iPhone SDK:如何通過互聯網向服務器發送數據?

回答

4
NSURL *cgiUrl = [NSURL URLWithString:@"http://yoursite.com/yourscript?yourargs=1"]; 
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:cgiUrl]; 

/* leave the rest out if just issuing a GET */ 
NSString *postBody = @"yourpostbodyargs=1"; 

NSString *contentType = @"application/x-www-form-urlencoded; charset=utf-8"; 
int contentLength = [postBody length]; 

[postRequest addValue:contentType forHTTPHeaderField:@"Content-Type"]; 
[postRequest addValue:[NSString stringWithFormat:@"%d",contentLength] forHTTPHeaderField:@"Content-Length"]; 
[postRequest setHTTPMethod:@"POST"]; 
[postRequest setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]]; 
/* until here - the line below issues the request */ 

NSURLConnection *conn = [NSURLConnection connectionWithRequest:postRequest delegate:self]; 

處理錯誤和接收到的數據:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    // data has the full response 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    contentLength = [response expectedContentLength]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)newdata 
{ 
    [data appendData:newdata]; 
} 

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
} 

你需要一些變量的設置,如數據,CONTENTLENGTH等。但是,這是HTTP交互的大致輪廓。

您可能希望將所有處理的東西放在單獨的處理程序類中,我將該代理程序更改爲self,因此這是更具自包含性的。

至於時機,使用NSTimer調用發佈數據每90秒:

[NSTimer scheduledTimerWithTimeInterval:90 target:self selector:@selector(xmitCoords) userInfo:nil repeats:YES]; 
+0

這是否意味着我必須先創建一個網站? – user3768495 2015-07-17 22:29:47

1

我覺得上面的回答有正確的想法 - 但嘗試使用ASIHTTPRequest。一個偉大的圖書館,它從你的程序中抽象出所有那些混亂的HTTP代碼。

另外還有一點需要注意 - 每90秒GPS座標將非常快地燒燬電池 - 您是否只是在做這個測試?

+0

不,但iPhone的磨練不斷插入電源,我也建立在選項完全關閉轉移或延長傳輸之間的時間長達一小時 – 2010-07-19 17:38:04

+0

有道理 - 只要小心,如果你做任何形式的「車隊跟蹤」和使用Google Maps API/MapKit - 違反了他們的服務條款。 此外,這個問題是否足夠回答? – makdad 2010-07-19 23:55:26

相關問題