이것은 서버의 내 PHP 파일입니다.
<?php
$results = Array(
Array(
"name" => "William",
"location" => "UK",
"action" => "Post Update"
),
Array(
"name" => "Sammy",
"location" => "US",
"action" => "posted news"
)
);
header("Content-Type: application/json");
echo json_encode($results);
?>
그리고 이것이 내가 신속하게 json 배열을 가져 오려고 시도하는 방법입니다.
let urlPath = "http://someurltophpserver"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if ((error) != nil) {
println("Error")
} else {
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
// do something with the data
}
})
task.resume()
다음 줄에서 앱이 충돌 let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
하며 오류가 발생합니다.
Could not cast value of type '__NSArrayM' (0x8c9b58) to 'NSDictionary' (0x8c9d74).
신속한 http 요청이 처음이므로 이것이 무엇을 의미하는지 완전히 확신하지 못합니다.
앱이 충돌하는 이유는 as!
. 선택 사항을 강제로 풀려고하므로 런타임 중에 이것이 실패하면 앱이 충돌합니다.
줄을 다음과 같이 변경하십시오.
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary
{
// Do stuff if jsonResult set with a value of type NSDictionary
}
이렇게하면 앱 충돌이 중지되지만 JSON serialiser가 반환하는 최상위 개체는 예상 NSArray
하지 못한 것이므로 NSDictionary
앱이 실제로 충돌 하는 이유 일 수 있습니다 . 당신은 컴파일러에게 "jsonResult를 NSDictionary가 될 값과 같게하자"라는 코드를 말합니다.
또한 일부 데이터를 다운로드하는 가장 쉬운 방법은 NSData(contentsOfURL:url)
. Grand Central Dispatch를 사용하여 백그라운드 큐에서 실행하여 메인 스레드 (UI)를 차단하지 않도록합니다.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let data = NSData(contentsOfURL: url)
// Run any other code on the main queue. Especially any UIKit method.
NSOperationQueue.mainQueue().addOperationWithBlock({
// Do stuff with data
})
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다