標籤:
非同步Post方式
1 // MARK: - 非同步Post方式 2 func asynchronousPost() 3 { 4 //建立NSURL對象 5 var url:NSURL! = NSURL(string: "http://m.weather.com.cn/data/101010100.html") 6 7 //建立請求對象 8 var request : NSMutableURLRequest = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10) 9 10 request.HTTPMethod = "POST"//佈建要求方式為POST,預設為GET11 12 var str:String = "type=focus-c";//設定參數13 var data:NSData = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!14 request.HTTPBody = data;15 16 //串連伺服器17 var connection = NSURLConnection(request: request, delegate: self)18 }19 20 21 22 // MARK: - NSURLConnectionDataDelegate23 func connection(connection: NSURLConnection, willSendRequest request: NSURLRequest, redirectResponse response: NSURLResponse?) -> NSURLRequest?24 {25 //將要發送請求26 return request27 }28 29 func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse)30 {31 //接收響應32 }33 34 35 var jsonData:NSMutableData = NSMutableData()36 func connection(connection: NSURLConnection, didReceiveData data: NSData)37 {38 //收到資料39 self.jsonData.appendData(data)40 }41 42 func connection(connection: NSURLConnection, needNewBodyStream request: NSURLRequest) -> NSInputStream?43 {44 //需要新的內容流45 return request.HTTPBodyStream46 }47 48 func connection(connection: NSURLConnection, didSendBodyData bytesWritten: Int, totalBytesWritten: Int, totalBytesExpectedToWrite: Int)49 {50 //發送資料請求51 }52 53 func connection(connection: NSURLConnection, willCacheResponse cachedResponse: NSCachedURLResponse) -> NSCachedURLResponse?54 {55 //緩衝響應56 return cachedResponse57 }58 59 func connectionDidFinishLoading(connection: NSURLConnection)60 {61 //請求結束62 63 var jsonString = NSString(data: self.jsonData, encoding: NSUTF8StringEncoding)64 65 println(jsonString)66 67 68 let dict:AnyObject? = NSJSONSerialization.JSONObjectWithData(self.jsonData, options: NSJSONReadingOptions.AllowFragments, error: nil)69 70 71 //已下代碼 重新修訂72 // var dic = dict as NSDictionary73 // 74 // let weatherinfoDic = dic.objectForKey("weatherinfo") as? NSDictionary75 // let city = weatherinfoDic?.objectForKey("city") as? String76 // let date_y = weatherinfoDic?.objectForKey("date_y") as? String77 // let temp1 = weatherinfoDic?.objectForKey("temp1") as? String78 // 79 // let alert = UIAlertView(title: (city! + date_y!), message: temp1!, delegate: nil, cancelButtonTitle: "確定")80 // alert.show()81 82 83 //2015年4月10號修改84 if var dic = dict as? NSDictionary85 {86 let weatherinfoDic = dic.objectForKey("weatherinfo") as? NSDictionary87 let city = weatherinfoDic?.objectForKey("city") as? String88 let date_y = weatherinfoDic?.objectForKey("date_y") as? String89 let temp1 = weatherinfoDic?.objectForKey("temp1") as? String90 91 let alert = UIAlertView(title: (city! + date_y!), message: temp1!, delegate: nil, cancelButtonTitle: "確定")92 alert.show()93 }94 }95
iOS開發——網路編程Swift篇&(六)非同步Post方式