0
嘿傢伙我試圖開發一個簡單的應用程序,從雅虎財經獲取數據。現在我可以從雅虎那裏得到JSON響應,但我只需要一個來自它的股票公司名稱的數據。那麼我怎麼能做到這一點?如何在Swift中顯示來自JSON的特定數據?
我的代碼:
import UIKit
class ViewController: UIViewController, NSURLConnectionDelegate {
lazy var data = NSMutableData()
override func viewDidLoad() {
super.viewDidLoad()
startConnection()
}
func startConnection(){
var baseUrl:NSURL = NSURL(string:"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22PETR4.SA%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=")!
var request: NSURLRequest = NSURLRequest(URL: baseUrl)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
// Recieved a new request, clear out the data object
self.data = NSMutableData()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
// Append the recieved chunk of data to our data object
self.data.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
// Request complete, self.data should now hold the resulting info
// Convert the retrieved data in to an object through JSON deserialization
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println(jsonResult)
}
}
響應:
{
query = {
count = 1;
created = "2015-01-17T04:34:11Z";
diagnostics = {
"build-version" = "0.2.212";
cache = {
content = 5d1e1de680846a307c9874dc3d6878dc;
"execution-start-time" = 4;
"execution-stop-time" = 5;
"execution-time" = 1;
method = GET;
type = MEMCACHED;
};
javascript = {
"execution-start-time" = 3;
"execution-stop-time" = 104;
"execution-time" = 101;
"instructions-used" = 66631;
"table-name" = "yahoo.finance.quotes";
};
publiclyCallable = true;
query = {
content = "select * from csv where [email protected] and columns='Ask,AverageDailyVolume,Bid,AskRealtime,BidRealtime,BookValue,Change&PercentChange,Change,Commission,Currency,ChangeRealtime,AfterHoursChangeRealtime,DividendShare,LastTradeDate,TradeDate,EarningsShare,ErrorIndicationreturnedforsymbolchangedinvalid,EPSEstimateCurrentYear,EPSEstimateNextYear,EPSEstimateNextQuarter,DaysLow,DaysHigh,YearLow,YearHigh,HoldingsGainPercent,AnnualizedGain,HoldingsGain,HoldingsGainPercentRealtime,HoldingsGainRealtime,MoreInfo,OrderBookRealtime,MarketCapitalization,MarketCapRealtime,EBITDA,ChangeFromYearLow,PercentChangeFromYearLow,LastTradeRealtimeWithTime,ChangePercentRealtime,ChangeFromYearHigh,PercebtChangeFromYearHigh,LastTradeWithTime,LastTradePriceOnly,HighLimit,LowLimit,DaysRange,DaysRangeRealtime,FiftydayMovingAverage,TwoHundreddayMovingAverage,ChangeFromTwoHundreddayMovingAverage,PercentChangeFromTwoHundreddayMovingAverage,ChangeFromFiftydayMovingAverage,PercentChangeFromFiftydayMovingAverage,Name,Notes,Open,PreviousClose,PricePaid,ChangeinPercent,PriceSales,PriceBook,ExDividendDate,PERatio,DividendPayDate,PERatioRealtime,PEGRatio,PriceEPSEstimateCurrentYear,PriceEPSEstimateNextYear,Symbol,SharesOwned,ShortRatio,LastTradeTime,TickerTrend,OneyrTargetPrice,Volume,HoldingsValue,HoldingsValueRealtime,YearRange,DaysValueChange,DaysValueChangeRealtime,StockExchange,DividendYield'";
"execution-start-time" = 5;
"execution-stop-time" = 95;
"execution-time" = 90;
params = "{url=[http://download.finance.yahoo.com/d/quotes.csv?f=aa2bb2b3b4cc1c3c4c6c8dd1d2ee1e7e8e9ghjkg1g3g4g5g6ii5j1j3j4j5j6k1k2k4k5ll1l2l3mm2m3m4m5m6m7m8nn4opp1p2p5p6qrr1r2r5r6r7ss1s7t1t7t8vv1v7ww1w4xy&s=PETR4.SA]}";
};
"service-time" = 91;
url = (
{
content = "http://www.datatables.org/yahoo/finance/yahoo.finance.quotes.xml";
"execution-start-time" = 1;
"execution-stop-time" = 1;
"execution-time" = 0;
},
{
content = "http://download.finance.yahoo.com/d/quotes.csv?f=aa2bb2b3b4cc1c3c4c6c8dd1d2ee1e7e8e9ghjkg1g3g4g5g6ii5j1j3j4j5j6k1k2k4k5ll1l2l3mm2m3m4m5m6m7m8nn4opp1p2p5p6qrr1r2r5r6r7ss1s7t1t7t8vv1v7ww1w4xy&s=PETR4.SA";
"execution-start-time" = 5;
"execution-stop-time" = 95;
"execution-time" = 90;
}
);
"user-time" = 106;
};
lang = "en-us";
results = {
quote = {
AfterHoursChangeRealtime = "N/A - N/A";
AnnualizedGain = "<null>";
Ask = "9.45";
AskRealtime = "9.45";
AverageDailyVolume = 80999600;
Bid = "9.44";
BidRealtime = "9.44";
BookValue = "27.652";
Change = "+0.10";
ChangeFromFiftydayMovingAverage = "-0.9209";
ChangeFromTwoHundreddayMovingAverage = "-7.3725";
ChangeFromYearHigh = "-15.46";
ChangeFromYearLow = "+1.40";
ChangePercentRealtime = "N/A - +1.07%";
ChangeRealtime = "+0.10";
"Change_PercentChange" = "+0.10 - +1.07%";
ChangeinPercent = "+1.07%";
Commission = "<null>";
Currency = BRL;
DaysHigh = "9.63";
DaysLow = "9.24";
DaysRange = "9.24 - 9.63";
DaysRangeRealtime = "N/A - N/A";
DaysValueChange = "- - +1.07%";
DaysValueChangeRealtime = "N/A - N/A";
DividendPayDate = "<null>";
DividendShare = "0.9672";
DividendYield = "10.36";
EBITDA = "66.171B";
EPSEstimateCurrentYear = "0.00";
EPSEstimateNextQuarter = "0.00";
EPSEstimateNextYear = "0.00";
EarningsShare = "1.535";
ErrorIndicationreturnedforsymbolchangedinvalid = "<null>";
ExDividendDate = "3-Apr-14";
FiftydayMovingAverage = "10.3609";
HighLimit = "<null>";
HoldingsGain = "<null>";
HoldingsGainPercent = "- - -";
HoldingsGainPercentRealtime = "N/A - N/A";
HoldingsGainRealtime = "<null>";
HoldingsValue = "<null>";
HoldingsValueRealtime = "<null>";
LastTradeDate = "1/16/2015";
LastTradePriceOnly = "9.44";
LastTradeRealtimeWithTime = "N/A - <b>9.44</b>";
LastTradeTime = "2:08pm";
LastTradeWithTime = "Jan 16 - <b>9.44</b>";
LowLimit = "<null>";
MarketCapRealtime = "<null>";
MarketCapitalization = "123.1B";
MoreInfo = cnpI;
Name = "PETROBRAS -PN";
Notes = "<null>";
OneyrTargetPrice = "<null>";
Open = "9.46";
OrderBookRealtime = "<null>";
PEGRatio = "<null>";
PERatio = "6.08";
PERatioRealtime = "<null>";
PercebtChangeFromYearHigh = "-62.09%";
PercentChange = "+1.07%";
PercentChangeFromFiftydayMovingAverage = "-8.89%";
PercentChangeFromTwoHundreddayMovingAverage = "-43.85%";
PercentChangeFromYearLow = "+17.41%";
PreviousClose = "9.34";
PriceBook = "0.34";
PriceEPSEstimateCurrentYear = "<null>";
PriceEPSEstimateNextYear = "<null>";
PricePaid = "<null>";
PriceSales = "0.38";
SharesOwned = "<null>";
ShortRatio = "<null>";
StockExchange = "Sao Paolo";
Symbol = "PETR4.SA";
TickerTrend = " ====== ";
TradeDate = "<null>";
TwoHundreddayMovingAverage = "16.8125";
Volume = 56271000;
YearHigh = "24.90";
YearLow = "8.04";
YearRange = "8.04 - 24.90";
symbol = "PETR4.SA";
};
};
};
}
我添加了代碼,但得到這個錯誤: '?AnyObject'沒有名爲'下標'的成員。 –
@Marco嘗試上面更新的代碼。你可能需要通過在它們後面加一個'!'來使這些類型成爲可選的(比如'NSDictionary!'),但這應該起作用。我會在早上看看它,應該有更乾淨的方式來做到這一點。 – Undo
現在它的作品!但我認爲它需要一種更清潔的方式。但是,謝謝! –