蔡秋俊 蔡秋俊 - 5 months ago 15
iOS Question

How to rewrite the following code into a swift version?

I just learning to swift, some problems in rewriting the OC code.

How to rewrite the following code into a swift version?

-(void)Postpath:(NSString *)path
{

NSURL *url = [NSURL URLWithString:path];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:10];

[request setHTTPMethod:@"POST"];


NSOperationQueue *queue = [NSOperationQueue new];

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data,NSError *error){
NSMutableDictionary *receiveStatusDic=[[NSMutableDictionary alloc]init];
if (data) {

NSDictionary *receiveDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
if ([[receiveDic valueForKey:@"resultCount"] intValue]>0) {

[receiveStatusDic setValue:@"1" forKey:@"status"];
[receiveStatusDic setValue:[[[receiveDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"version"] forKey:@"version"];
}else{

[receiveStatusDic setValue:@"-1" forKey:@"status"];
}
}else{
[receiveStatusDic setValue:@"-1" forKey:@"status"];
}

[self performSelectorOnMainThread:@selector(receiveData:) withObject:receiveStatusDic waitUntilDone:NO];
}];

}


How should I rewrite?

Answer
  func Postpath(path: String) {
        var url: NSURL = NSURL(string: path)!


        var request : NSMutableURLRequest = NSMutableURLRequest(URL: url);
        request.HTTPMethod = "POST"
        var queue: NSOperationQueue = NSOperationQueue()

        NSURLConnection.sendAsynchronousRequest(request, queue: queue) { (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

            var receiveStatusDic: NSMutableDictionary = NSMutableDictionary()
            if data != nil {
                var receiveDic: NSDictionary = NSDictionary();
                do {
                    receiveDic = try  NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as! NSDictionary
                } catch {
                    print(error)
                }

                if ((receiveDic.valueForKey("resultCount")?.intValue) > 0)  {

                    receiveStatusDic.setValue("1", forKey:"status")
                    receiveStatusDic.setValue(receiveDic.valueForKey("results")?.objectAtIndex(0).valueForKey("version"), forKey:"version")
                }
                else {

                    receiveStatusDic.setValue("-1", forKey:"status")
                }
            }
            else {
                  receiveStatusDic.setValue("-1", forKey:"status")
            }
            self.performSelectorOnMainThread("receiveData:", withObject: receiveStatusDic, waitUntilDone: false)
        }

you can use this code .