我需要实现一个可以多次使用的函数

时间:2017-03-03 07:08:05

标签: objective-c multithreading swift3 singleton

我有一个快速的功能,我想转换成目标C可以帮助我转换它吗?任何帮助将不胜感激

     func getdata(_ send: NSString)
    {

        let url=URL(string:send as String)
        do
        {
            let allContactsData = try Data(contentsOf: url!)
            let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
            print(allContacts)
            if let musicJob = allContacts["Attendance"] as? [Any], !musicJob.isEmpty
            {
                print(musicJob)
                dataArray = allContacts["Attendance"] as! NSArray
                print(dataArray)

            }
}
           { let send: String = String(format:"http://182.18.182.91/RaosMobileService/Service1.svc/GetStudentAttendance_ByMonth/%@/%@/1/%d/2017",loadedUserName,studentId,row+1)
            self.getdata(send as NSString)
}
  

如何将其转换为目标C,任何帮助请。我需要使用这个func getdata(_ send:NSString)   多次

1 个答案:

答案 0 :(得分:0)

目标-c

NSJSONSerialization

尝试1:如果Json返回数组

 -(void)getdata:(NSString *)send
    {
        NSURL *url = [[NSURL alloc]initWithString:send];
        NSData *data = [[NSData alloc] initWithContentsOfURL:url];

        NSError *e = nil;
        NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];

        if (!jsonArray) {
            NSLog(@"Error parsing JSON: %@", e);
        } else {
            for(NSDictionary *item in jsonArray) {
                NSLog(@"Item: %@", item);
            }
        }
    }

尝试2:如果Json返回Dictinary

-(void)getdata:(NSString *)send
{
    NSURL *url = [[NSURL alloc]initWithString:send];
    NSData *data = [[NSData alloc] initWithContentsOfURL:url];

    NSDictionary *res     = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@",res);
 }

致电方法:

  NSString *send = [NSString stringWithFormat:@"http://182.18.182.91/RaosMobileService/Service1.svc/GetStudentAttendance_ByMonth/%@/%@/1/%d/2017"];
    [self getdata:send];