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를' 'subscript'라는 멤버가 없습니다. –
@Marco 위의 업데이트 된 코드를 사용해보십시오. 'NSDictionary! '와 같이'!'를 추가하여 타입을 선택적으로 만들어야 할 수도 있지만, 이것이 가능합니다. 나는 그것을 아침에 보게 될 것이다. 이것을하기위한 더 깨끗한 방법이 있어야한다. – Undo
이제 작동합니다 !!!! 그러나 나는 그것이 더 깨끗한 길을 필요로한다고 생각한다. 하지만 고마워요 !!! –