我在xcode游乐场中创建了一小段代码。 (请参阅附件链接)并得到2个问题。
enter image description here 代码:
import PlaygroundSupport
import Foundation
PlaygroundPage.current.needsIndefiniteExecution = true
//https://newsapi.org visit website to get API key
parseURL(theURL: "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=c65fbb5007484819a3529c4f8c05adf1")
func parseURL(theURL:String){
let url = URL(string: theURL)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
// is there an error? Error handling section
if error != nil {
print("did not work, \ (String(describing: error))")
DispatchQueue.main.asyncAfter(deadline: .now() ) { //
// just deal
}
// end of Error handling section
} else {
do {
let parsedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
for (key, value) in parsedData {
if (key == "articles") {
print (value)
}
if (key == "author") {
print (value)
}
}
// end of JSON parsing section
} catch let error as NSError {
print(error)
DispatchQueue.main.asyncAfter(deadline: .now() ) { //
// Just Deal
}
}
}
}.resume()
} //end of function
我确实获得了json信息。
问题1。 为什么我在第6行收到一条错误消息,提示“使用未解析的标识符'parseURL'”。它可以正常工作,并且确实将数据提供给函数。
问题2。 当我将代码从操场移到xcode iOS应用开发人员区域时,由于第6行中的错误,它甚至无法编译并提供数据(并且我确实需要将打印行链接到情节提要中)>
希望您能帮助我解释我做错了什么。