0
我正在學習使用外部數據庫,我使用mysql + php。數據結構非常簡單。我只有1個表格「發佈」,具有4個屬性:標識,標題,作者和內容。然後我試圖從在線視頻使用NSArray和NSDictionary:無法將類型「字符串」的值轉換爲預期的參數類型「int」
學習,如果我複製了確切的代碼,它可以成功地建立,後來就傳來了錯誤信息
「無法投類型的值‘__NSArrayM’(0x882178)到 'NSDictionary'(0x882394)。「
在
let response = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary".
編碼所以我在編碼改變了NSDictionary
到NSArray
,那麼它出來另一個錯誤的另一種編碼,甚至無法成功建立。
在
self.loadPosts(response["posts"] as! NSArray)
現在我也不做什麼和編碼「無法轉換類型「字符串的值」,以期望的參數‘INT’
請幫幫我。
這些都是編碼後service.swift
import Foundation
class PostService {
var settings:Settings
init() {
self.settings = Settings()
}
func getPosts(callback:(NSArray) ->()){
request(settings.viewPosts, callback: callback)
}
func request(url:String, callback:(NSArray) ->()){
let nsURL = NSURL(string: url)
let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!)
{(data,response,error) in
let _: NSError
let response = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
callback (response)
}
task.resume()
}
}
下面的代碼是在masterviewcontroller.swift
:
var detailViewController: DetailViewController? = nil
var postsCollection = [Post]()
var service:PostService!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
service = PostService()
service.getPosts{
(response) in
self.loadPosts(response["posts"] as! NSArray)
}
}
// func loadPosts
func loadPosts (posts:NSArray){
for post in posts {
let id = post["Post"]!!["id"] as! String
let title = post["Post"]!!["title"] as! String
let author = post["Post"]!!["author"] as! String
let content = post["Post"]!!["content"] as! String
let postObj = Post(id: id, title: title, author: author, content: content)
postsCollection.append(postObj)
dispatch_async(dispatch_get_main_queue()){
self.tableView.reloadData()
}
}
}