0
我试图从服务器加载图像到我的ios应用程序与GET请求的帮助。然而它显示出一些含糊不清。任何人都可以请帮忙。这里是低于code`
进口的UIKit模糊引用成员'jsonObject(与:选项:)
类的ViewController:UIViewController中,UICollectionViewDelegate,UICollectionViewDataSource { @IBOutlet VAR MyCollectionView:UICollectionView!
var images : [String] = []
override func viewDidLoad() {
super.viewDidLoad()
loadImages()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//MyCollectionViewCell
let myCell:MyCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! MyCollectionViewCell
DispatchQueue.global(qos: .background).async{
let imageString = self.images[indexPath.row]
let imageUrl = NSURL(string: imageString)
let imageData = NSData(contentsOf: imageUrl! as URL)
DispatchQueue.main.async {
//if(imageData! = nil)
//{
myCell.myImageView.image = UIImage(data: imageData! as Data)
//}//end of if
}//end of DispatchQueue.main.async
};//end of main dispatch
return myCell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("User tapped on image # \(indexPath.row)")
}
func loadImages()
{
let startTime = NSDate.timeIntervalSinceReferenceDate
var pageUrl = "Url is here"
let myUrl = NSURL(string: pageUrl)
let request = NSMutableURLRequest(url:myUrl! as URL)
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
//If error displays any alert message
if error != nil {
var myAlert = UIAlertController(title: "Alert", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
myAlert.addAction(okAction)
self.present(myAlert, animated: true, completion: nil)
return
}
var err: NSError?
if let usabledata = data{
do{
var jsonArray = try JSONSerialization.jsonObject(with: usabledata, options: .mutableContainers) as! [String:AnyObject]
print(jsonArray)
//conditional binding error here
if let parseJSONArray = jsonArray {
self.images = parseJSONArray as! [String]
DispatchQueue.main.async(execute: {
self.MyCollectionView.reloadData()
})//end of dispatchQueue
}//end of if
}catch{
print(error)
}
}
}
task.resume()
}
}
@himesh是解决方案为你工作? – KKRocks
我确实取代了它。它说条件绑定initinitizer必须有可选类型,而不是'[String:AnyObject]' – himesh
你可以发布你的整个代码与这个答案? – KKRocks