转换数据?包含字节到int in swift 5

时间:2019-04-10 10:38:57

标签: swift type-conversion

我从IoS上ble外围设备的特征中读取了一些数据,当我尝试打印它们时,它只说了2个字节。查看类型,它是可选的数据类型(数据?)。

我的问题是,要将值转换为可读的整数,最快5最快的做法是什么?

如果我尝试打印character.value,它只会显示“ 2个字节”。 character.value是可选的数据类型。

public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {


    public JWTLoginFilter(String url, AuthenticationManager authenticationManager) {
        super(new AntPathRequestMatcher(url));
        setAuthenticationManager(authenticationManager);
        tokenAuthenticationService = new TokenAuthenticationService();

    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {

        LOGGER.info("Attempting Authentication....");

        ServletInputStream res = httpServletRequest.getInputStream();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(Feature.AUTO_CLOSE_SOURCE, true);
        User credentials = objectMapper.readValue(res, User.class);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUserName(),
                new String(Base64.getDecoder().decode(credentials.getPassword()))

        );
        return getAuthenticationManager().authenticate(token);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
            Authentication authentication) throws IOException, ServletException {
        LOGGER.info(" After Successful Authentication with ...");
        String name = authentication.getName();
        LOGGER.info(" Adding Token in Headers......");
        tokenAuthenticationService.addAuthentication(response, name); // Custom Service Class
    }

}


@Component
public class JWTAuthenticationFilter extends GenericFilterBean { //

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        Authentication authentication = new TokenAuthenticationService().getAuthentication((HttpServletRequest) request);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        filterChain.doFilter(request, response);
    }

}

非常感谢您!

1 个答案:

答案 0 :(得分:0)

尝试一下:

guard let value = characteristic.value else { return } // This makes it non-optional
let stringInt = String(data: value, encoding: .utf8)
let yourNumber = Int(stringInt)

这比下面的示例安全得多。首选上述一种。

在一行代码中:

let yourNumber = Int(String(data: characteristic.value!, encoding: .utf8))

这是不安全的,因为您展开的值可能是可选的,这可能会导致崩溃。

希望这会有所帮助!