2015-09-21 88 views
2

我正在研究iOS應用程序,其基礎是Objective-C與AFNetworking與API進行通信。現在我在Swift中編寫新的ViewControllers,並且在Swift文件中的CompletionBlock中遇到了一些問題。完成塊AFNetworking在Swift

原來的Objective-C代碼:

- (void)downloadJson { 
    [[ODDWebService sharedInstance] getParkingSpacesWithCompletionBlock:^(NSArray *result, BOOL succes) { 
     if(succes) { 
      [self.parkings removeAllObjects]; 

      for(NSDictionary *dict in result) { 
       Parking *parking = [[Parking alloc] init]; 
       parking.name = [dict objectForKey:@"name"]; 
       parking.freespace = [[dict objectForKey:@"freespace"] integerValue]; 
       [self.parkings addObject:parking]; 
      } 
      [self updateParkings]; 
     } else { 
      NSLog(@"ERROR RETRIEVING PARKING SPACES"); 
     } 
    }]; 
} 

這是我認爲它應該是在斯威夫特:

func downloadJson() { 
    ODDWebService.sharedInstance().getParkingSpacesWithCompletionBlock { (result: AnyObject, succes: Bool) -> Void in 
     if(succes) { 
      self.parkings.removeAllObjects() 

      for dict: NSDictionary in result { 
       var parking: Parking = Parking 
       parking.name = dict["name"] 
       parking.freespace = dict["freespace"].integerValue() 
       parkings.addObject(parking) 
      } else { 
       NSLog("ERROR RETRIEVING PARKING SPACES") 
      } 
     } 
    } 
} 

主要錯誤是在第二行代碼中發現:

'(AnyObject, Bool) -> Void' is not convertible to '(([AnyObject]!, Bool) -> Void)!' 
+0

只需添加「!」在任何對象之後ODDWebService.sharedInstance()。getParkingSpacesWithCompletionBlock {(result:AnyObject!,succes:Bool) - >無效 –

+0

當我這樣做,ViewController中的錯誤消失,但我得到一個命令失敗,由於信號:分段錯誤:11. – Ruben

回答

0

更換

func downloadJson() { 
ODDWebService.sharedInstance().getParkingSpacesWithCompletionBlock { (result: AnyObject, succes: Bool) -> Void in 
    if(succes) { 

隨着

func downloadJson() { 
ODDWebService.sharedInstance().getParkingSpacesWithCompletionBlock { 
result, success in 
    if(succes) { 

同時添加的第一行下面的代碼到你的代碼。

if let dicts = result as? NSDictionary<String, AnyObject> { 
for dict: NSDictionary in dicts { 
      var parking: Parking = Parking 
      parking.name = dict["name"] 
+0

這也解決了第一個問題,但'爲字典:結果{'行中的NSDictionary仍給出錯誤''[AnyObject]!'不可轉換爲'NSDictionary'' – Ruben

+0

我編輯了答案。希望這對你有用。 – Vakas

+0

現在我得到了一個新的警告,如果讓字典行:'從'[AnyObject]投!'到不相關的類型'[String:AnyObject]'總是失敗'並且字典行上的錯誤:''[String:AnyObject]'不能轉換爲'NSDictionary'' – Ruben

0

您正試圖將NSArray強制轉換爲Anyobject。你可以試試這個代碼:

func downloadJson() { 
    ODDWebService.sharedInstance().getParkingSpacesWithCompletionBlock { (result: [AnyObject]!, success: Bool) -> Void in 
     if(succes) { 
      self.parkings.removeAllObjects() 

      for dict in result as NSArray { 
       var parking: Parking = Parking 
       parking.name = dict["name"] 
       parking.freespace = dict["freespace"].integerValue() 
       parkings.addObject(parking) 
      } else { 
       NSLog("ERROR RETRIEVING PARKING SPACES") 
      } 
     } 
    } 
} 
+0

偉大的這解決了第一個問題,但現在我收到消息: '[AnyObject]!'不能轉換爲'NSDictionary'' – Ruben

相關問題